Installing a Node.js App as a regular GNU/Linux process

While in development of any Node.js application we usually configure a npm start task to run it; but when you are ready to go to production that concept is not useful anymore. Until that moment, we have tested our application using the regular npm process (npm start); but now, we are going to need to go one step further. We will install a process manager for Node.js called PM2:

PM2 will allow us to register our Node.js application as a regular process in GNU/Linux.

1) Install PM2:

sudo npm install pm2 -g

2) Run pm2 start command to run the application:

// This also adds the application to PM2's process list, 
// which is outputted every time you start an application
sudo pm2 start /path/to/main/nodejs/script

// For example:
sudo pm2 start /usr/share/nginx/html/wetraining-chat/server.js

Figure 1. Example of server process in PM2.

PM2 automatically assigns an Application name and a PM2 id. In this case since the file is “server.js”; the resulting process would be “server”. PM2 also maintains other information, such as the PID of the process, its current status, and memory usage.

Applications running under PM2 will be restarted automatically if the application crashes or is killed, but an additional step needs to be taken to get the application to launch on system startup (boot or reboot). To solve this, PM2 provides the startup subcommand.

The startup subcommand generates and configures a startup script to launch PM2 and its managed processes on server boots. You must also specify the platform you are running on, which is ubuntu, in our case:

sudo pm2 startup ubuntu

Useful PM2 commands

// Stop the application
pm2 stop APP_NAME
// Restart an application
sudo pm2 restart APP_NAME
// List the applications currently managed by PM2
sudo pm2 list
// Get meta-data about an application
sudo pm2 info APP_NAME
// Display the application status, CPU, and memory usage
sudo pm2 monit

I hope you find this information useful. PM2 is an excellent option to register our Node.js app as regular GNU/Linux. There are other options out there like Strong Loop Process Manager and Forever. Have you used one of them? Let me know your opinion.

Leave a Reply

Your email address will not be published. Required fields are marked *