Process Management

Thus far, you've been running your web service directly from your terminal with the command node index.js. The service runs as long as you are logged in to your server. But you don't want to stay logged in forever. Perhaps you could run your service in the background. Even then, many shells kill background processes when you exit. You need a process manager.

The PM2 package on NPM is one such process manager. It runs your service in a backgrounded process and keeps it running after you log out. It collects your service's logs. If your service crashes, it will automatically restart it.

You install PM2 with this command:

npm install -g pm2

This installs PM2 globally rather than just inside your project. A global installation will make it easier to manage multiple processes. This installation goes smoothly using the Node.js tooling installed with NVM. Global installations using a system-wide Node.js installation generally end in permission issues.

Inside your service directory, you start up the service with this command:

pm2 start index.js --name unforget-api

The --name unforget-api arguments give the process a meaningful name that you will use in later commands.

Try accessing your web service with curl or your browser. Then log out from your service and try accessing it again. Does it still work?

Try logging back in to your web service and running this command:

pm2 status

Note the numeric process ID (pid) of the service you just started. Run this command to kill the service process:

kill YOUR-PID

Check the status again. Notice how the service has been restarted and now has a different process ID? Restarting crashed services is a feature of PM2.

Run this command to check the logs, which are updated live as the service responds to requests:

pm2 log unforget-api

If you make a change to index.js or scripts it depends on, PM2 does not automatically restart the process. You must do that explicitly with this command:

pm2 restart unforget-api

If you want to take your service offline, killing the process isn't enough. You must release it from PM2's grasp with the delete command:

pm2 delete unforget-api

The PM2 documentation describes the full set of commands in detail.