PM2 is straightforward, it is offered as a simple and intuitive CLI, installable via NPM. Just start your application with PM2 to boost your application and to make it ready to handle a ton of traffic!
Installation
The latest PM2 stable version is installable via NPM:
npm install pm2@latest -g
Above will install the latest version and if its running then you need update the in-memory version by running following command
pm2 update
Usage
The simplest way to start, daemonize and monitor your application is by using this command line:
pm2 start app.js
Application declaration
You can also create a configuration file to manage multiple applications:
process.yml:
apps:
- script : app.js
instances: 4
exec_mode: cluster
- script : worker.js
watch : true
env :
NODE_ENV: development
env_production:
NODE_ENV: production
And start it easily:
pm2 start process.yml
Read more about application declaration here.
Setup startup script
Restarting PM2 with the processes you manage on server boot/reboot is critical. To solve this, just run this command to generate an active startup script:
pm2 startup
Stop PM2 process
pm2 kill
Stop an instance running under PM2
pm2 stop <<instance_id>>
pm2 stop 0
If you want to stop all running instances
pm2 stop all
Cluster setup
pm2 start server.js -i max
"max" is deprecated and instead of that you can supply 0 pm2 start server.js -i 0
This will roll out maximum number of instance based on no of core available in the server
Supply parameter while initiate an instance
pm2 start server.js -- DEV
In above example, DEV is the parameter value supplied
pm2 start -i 0 server.js -- PARAM1 PARAM2
Above one roll out maximum no of instances based of no of core available and supplying PARAM1 & PARAM2
To display logs (especially the startup logs which includes console.log in express application)
pm2 logs startup
To see metrics & detail of a particular running instance
pm2 show <<instance_id>>
To monitor all running instance with metrics & meta details
pm2 monit
pm2 show 0
To see all environment variable available for the particular instance
pm2 env <<instance_id>>
pm2 env 0