How to pass execution arguments to app using PM2?
Solution 1:
If you want to pass node arguments from CLI then
pm2 start myServer.js --node-args="--production --port=1337"
.
Edited
you can add any arguments after --
pm2 start app.js -- --prod --second-arg --third-arg
Sails docs for deploymemt.
Solution 2:
You can do as stated in this ticket: https://github.com/Unitech/pm2/issues/13
Though if you're passing the environment you may want to consider leveraging environment variables. With this you create a variable which can be accessed by any process in that environment with process.env.*
.
So you have a configuration file config.json
:
{
"dev": {
"db": {
"hosts":["localhost"],
"database": "api"
},
"redis": {
"hosts": ["localhost"]
}
},
"staging": {
"db": {
"hosts":["1.1.1.1"],
"database": "api"
},
"redis": {
"hosts": ["2.2.2.2"]
}
},
"production": {
"db": {
"hosts":["1.1.1.1", "1.1.1.2", "1.1.1.3"],
"database": "api"
},
"redis": {
"hosts": ["2.2.2.2", "2.2.2.3"]
}
}
}
Then you import your config:
var config=require('./config.json')[process.env.NODE_ENV || 'dev'];
db.connect(config.db.hosts, config.db.database);
Then you'd set the variable in your environment via shell:
export NODE_ENV=staging
pm2 start app.js
The environment variable will last as long as your session. So you'll have to set it in the ~/.bashrc
file for that user for the variable to persist. This will set the variable every session.
PM2 has a deploy system which allows you to set an environment variable each time before your app is daemonized. This is how daemons in POSIX systems typically take parameters, because those parameters aren't lost with the process. Given with your circumstance it might not matter so much, but its a good practice.
Moreover you should consider stop/starting locally, and restarting(if in cluster mode) whenever possible to prevent downtime when in production.
Solution 3:
It is possible to define arguments with the process.
You can define a new process in ecosystem.config.js
with an args
key, like so:
{
name : 'my-service',
script : './src/service.js',
args : 'firstArg secondArg',
},
{
name : 'my-service-alternate',
script : './src/service.js',
args : 'altFirstArg altSecondArg',
}
Here, the two processes use the same file (service.js
), but pass different arguments to it.
Note that these arguments are handled within service.js
.
In my case I just used process.argv[2]
to get the first argument, and so on.