PM2 is a process manager for NodeJS. PM2 will restart your node processes if they crash and keep track of the number of restarts. You can also connect your processes to keymetrics.io so you can monitor remotely.

Installing PM2

Install PM2 globally via NPM to use it.

$ npm install -g pm2

Using PM2

Normally you would run your NodeJS processes like this:

$ node /sites/my-site/server.js

With PM2, you would run your process like this:

$ pm2 start /sites/my-site/server.js

Then something like this would display:

┌──────────┬────┬──────┬───────┬────────┬─────────┬────────┬────────────┬──────────┐
│ App name │ id │ mode │ pid   │ status │ restart │ uptime │ memory     │ watching │
├──────────┼────┼──────┼───────┼────────┼─────────┼────────┼────────────┼──────────┤
│ server   │ 0  │ fork │ 12044 │ online │ 0       │ 0s     │ 9.828 MB   │ disabled │
└──────────┴────┴──────┴───────┴────────┴─────────┴────────┴────────────┴──────────┘

The App name column identifies the process that is running. By default, it will use the name of the script you started. You can customize it by doing the following:

$ pm2 start /sites/my-site/server.js --my-site

If you make a change to the script, you can restart it using the app name or the id like such:

$ pm2 restart my-site
$ pm2 restart 0

Or you can watch the current directory and it's sub-directory for changes...

$ cd /sites/my-site
$ pm2 start server.js --name=my-site --watch

Then whenever a file changes, the process will restart.

To stop watching, you need to explicitly stop the process with the watch argument.

$ pm2 stop my-site --watch

Restarting processes on server reboot is really easy, too:

$ pm2 startup
$ pm2 save

For full documentation on PM2 and to learn about all the other cool stuff you can do with it, visit the keymetrics site at http://pm2.keymetrics.io/.