Get started with the basics of PM2 and learn how to run your Node.js apps in the background using Node.js process manager PM2.
PM2 is a daemon process manager that will help you manage and keep your Node.js application online 24/7. It’s a production grade process manager that let’s your node.js applications run in the background as microservices. PM2 also works in shell scripts, python and binary files.
Install PM2
Install PM2 globally using the following command. To start using PM2, you need npm and Node.js installed, of course!
$ npm install PM2@latest -g # or $ yarn global add PM2
Start a Node application using PM2
To start a Node.js application, just use the following command.
$ pm2 start app.js
This command returns an id, which can be used to stop, restart or delete the app.
[PM2] Starting /home/demo/package/index.js in fork_mode (1 instance) [PM2] Done. ┌─────┬─────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐ │ id │ name │ namespace │ version │ mode │ pid │ uptime │ ↺ │ status │ cpu │ mem │ user │ watching │ ├─────┼─────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤ │ 0 │ index │ default │ 4.9.0 │ fork │ 21568 │ 0s │ 0 │ online │ 0% │ 5.8mb │ sch… │ disabled │ └─────┴─────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
To give a name to your running instance, pass name using –name
$ pm2 start app.js --name demo-app
You can stop, restart or delete this running node app with its name.
[PM2] Starting /home/demo/package/index.js in fork_mode (1 instance) [PM2] Done. ┌─────┬─────────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐ │ id │ name │ namespace │ version │ mode │ pid │ uptime │ ↺ │ status │ cpu │ mem │ user │ watching │ ├─────┼─────────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤ │ 1 │ demo-app │ default │ 4.9.0 │ fork │ 11360 │ 0s │ 0 │ online │ 0% │ 9.0mb │ sch… │ disabled │ └─────┴─────────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
Stopping a Node application using pm2
pm2 stop <id> #or pm2 stop <name>
Deleting a Node application using pm2
pm2 delete <id> #or pm2 delete <name>
To stop all pm2 processes
pm2 stop all
To restart all pm2 processes
pm2 restart all
To reload all pm2 processes
pm2 reload all
To delete all pm2 processes
pm2 delete all
To view all pm2 processes
pm2 list