How To Run NodeJS Applications in Production using PM2

NodeJS isn’t a process manager, meaning when you run your application using NPM or NodeJS directly the application will not restart when problems are encountered. This behaviour is not desirable in any production environments.

To successfully run your NodeJS-based application, such as an Express RESTful API, you will need to use a process manager. The most popular manager for Node application is PM2, which doubles as a load balancer as well.

In this tutorial I will guide you through running your NodeJS applications in production with confidence.

Install Node and NPM

Since PM2 is a publicly available service written for NodeJS, we install it using NPM. In order to do that we must install NodeJS and NPM prior to installing PM2.

install node

Install PM2

Installing PM2 is done through NPM module repository. The installation needs to be done globally to allow any Node application to be managed by it.

sudo npm install -g pm2

Create System Account for PM2

Like any service running on a server, PM2 should run under its own user context. By doing so we eliminate a large security hole and minimize the amount of damage a hacker can do via a vulnerability in PM2.

When running as root becomes compromised, a hacker can obtain root level privileges to your server. By running your service with an unprivileged user account, we decrease our security footprint and decrease the amount of damage that can be done.

The following we create a service account named pm2. The -r flag is used to set the account as a system account, which provides an extra layer of security, such as not allowing logons.

useradd -r -c "pm2 service account" pm2 

Service accounts should never be used for anything other than the service they were created for. It merely exists to run a process and nothing more. By using the -f flag, we remove the ability to remotely log in as the service account, which removes a possible attack vector.

Auto Starting PM2 at Boot

Run the following command to automatically start PM2 after a system boot. Not only will this command instruct systemd to run PM2 at boot, it will run it under the context of our previously generated pm2 system account within the pm2 account’s home directory.

sudo env PATH=%PATH/usr/bin /usr/local/lib/node_modules/pm2/bin/pm2 startup systemd -u pm2 -hp /home/pm2

Running Your App from PM2

With PM2 installed we can now run our app.