Issue
I am running my nodejs code via PM2. For my project I need multiple instances of nodejs that running the same code. So I created a next script "myscript.sh":
cd ~/myproject
PM2_HOME='.pm2_1' /usr/local/bin/node /usr/local/lib/node_modules/pm2/bin/pm2 start dist/app.js -- id=1 token=xxx isMaster=true
PM2_HOME='.pm2_2' /usr/local/bin/node /usr/local/lib/node_modules/pm2/bin/pm2 start dist/app.js -- id=1 token=yyy isMaster=false
. . .
PM2_HOME='.pm2_x' /usr/local/bin/node /usr/local/lib/node_modules/pm2/bin/pm2 start dist/app.js -- id=1 token=zzz isMaster=false
It works when I run it via CLI like bash myscript.sh
, but it doesn't work via crontab:
@reboot bash /home/user/myproject/myscript.sh
or
* * * * * bash /home/user/myproject/myscript.sh
Also I tried to use pm2 startup
but it doesn't work with the PM2_HOME='..'
parameter, no matter what I set to PM2_HOME
, like .pm2_1, it still creates environment like /home/user/myproject/.pm2. Seems like pm2 startup
works for the single instances only.
So my question how can I run myscript.sh via crontab?
I don't know if it relevant my code is written in TS. On localhost I run it like this:
npm start -- id=1 token=zzz isMaster=false
where start is set in package.json:
"start": "npm run build && node dist/app"
"build": "rimraf dist && tsc"
Please notice that
- Every instance should get different parameters
- Solution should work for the startup case, like the app should startup with a machine start
Solution
To have PM2 run multiple instances of your node app you'll want to use clustered mode.
See the docs here: https://pm2.keymetrics.io/docs/usage/cluster-mode/
For example, you can use this command to start 4 instances of your app:
pm2 start app.js -i 4
--- EDIT ---
For providing different input parameters per process I don't think there is any easy way to do that with PM2.
An alternative is to create a new JavaScript/TypeScript file as your entry point. Have that entry point create multiple child processes, each of which is your application. Then you could pass in different parameters for each.
Answered By - James Answer Checked By - Marie Seifert (WPSolving Admin)