We are running our Node.js process inside an ephemeral SSH session. When we log out, the host machine will kill any processes initiated during that session. Therefore, we need to come up with a way of keeping our process alive even after logging out.
Furthermore, no matter how good our code base is, or how complete our test plans are, in any application of significant size, there will be errors. Sometimes, these errors are fatal and crash the application. In these instances, we should log the error and notify the developers, but most importantly, we should restart the application as soon as it crashes.
Ubuntu provides the upstart daemon (upstart.ubuntu.com), which can monitor a service and respawn it if it dies unexpectedly. Likewise, there's a popular npm package called forever (github.com/foreverjs/forever), which does a similar job. However, I have found PM2 (pm2.keymetrics.io) to be the best process manager out there, so that's what we'll use in this book.
First, install PM2 as a development dependency:
$ yarn add pm2 --dev
Then, update our serve npm scripts to execute pm2 start instead of node:
"serve": "yarn run build && dotenv -e envs/.env pm2 start dist/index.js"
Now, push these changes from your local machine and pull them into the virtual server. Run yarn again to install pm2 and then run yarn run serve; now, our process is managed by PM2 and not our hobnob user. This means even if you log out or disconnect, our Node.js process would still continue to run:
hobnob@hobnob:$ yarn run serve
...
[PM2] Starting /home/hobnob/projects/hobnob/dist/index.js in fork_mode (1 instance)
[PM2] Done.
┌──────────┬────┬───────┬────────┬─────────┬────────┬─────┬─────────┐
│ App name │ id │ pid │ status │ restart │ uptime │ cpu │ mem │
├──────────┼────┼───────┼────────┼─────────┼────────┼─────┼─────────┤
│ index │ 0 │ 15540 │ online │ 0 │ 0s │ 1% │ 21.9 MB │
└──────────┴────┴───────┴────────┴─────────┴────────┴─────┴─────────┘
Use `pm2 show <id|name>` to get more details about an app
The great thing about PM2 is that the user interface is fantastic for a CLI tool. If we run npx pm2 monit, you'll get a dashboard with all the running processes, and you can use the mouse to see the status, resource usage, and other statistics in real time:
┌─ Process list ────┐┌─ Global Logs ──────┐
│[ 0] index ││ │
└───────────────────┘└────────────────────┘
┌─ Custom metrics ─┐┌─ Metadata ─────────┐
│ Loop delay o ││ App Name index │
│ de-metrics) ││ Restarts 0 │
│ ││ Uptime 10m │
└───────────────────┘└────────────────────┘