I am starting instances of my app as a package.json
script with PM2 this way:
"start:pm2": "pm2 start -i max node myapp.js"
I found out that not all members in the team always want to use max
as a value for instances number while developing, but prefer to use some lower value.
To not change package.json
I would better let them change the value inside .env
file because we already use it so that the value from it would be used as the parameter to pm2.
I know I can create a wrapper js or bash script to load the variable from .env
file and pass it to pm2 but it would be better to have a solution without it.
How can I achieve this?
You can create an ecosystem.config.js
file and declare your environment variables under the “env:” attribute, in your case the NODE_APP_INSTANCE
can be used to set the number of instances:
module.exports = {
apps : [{
name: "MyApp",
script: "./myapp.js",
env: {
NODE_ENV: "development",
NODE_APP_INSTANCE: "max"
},
env_production: {
NODE_ENV: "production",
}
}]
}
Then call pm2 start
or pm2 start /path/to/ecosystem.config.js
to load an ecosystem from an other folder.
A better pattern here is to remove dotenv from your code and "require" it on the command line. This makes your code nicely transportable between any environment (including cloud-based) - which is one of the main features of environment variables.
a) code up your.env file alongside your script (eg app.js)
b) to run your script without pm2:
node -r dotenv/config app.js
c) in pm2.config.js:
module.exports = {
apps : [{
name : 'My Application',
script : 'app.js',
node_args : '-r dotenv/config',
...
}],
}
and then pm2 start pm2.config.js
Note: the use of dotenv/config on the command line is one of the best practices recommended by dotenv themselves
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.