Deploy nodejs application PM2 | Divyansh Rai


Deploy nodejs application PM2

We are going to explore the PM2 process manager. We will start with an overview of how to install it and use it to get a basic Nodejs application ready for production within minutes.

Then we will go on to see some of the benefits of using PM2.

Why use PM2

Application managers are an essential utility in the tool set of every developer and operations engineer. They allow for quick and convenient application configuration so that all it takes to get an application ready for production or development is a few quick commands.

Furthermore, they make managing services and processes scalable. Although there are other similar solutions available, such as Docker, Kubernetes, and Linux Containers, the PM2 application manager has been developed with Nodejs applications in mind.


Let’s get started by first installing PM2 using a package manager from the command line:

$ npm i pm2 -g

Example Application Setup

We are going to be using a basic express application in order to demonstrate PM2’s application management capabilities:

$ npm create -y$ npm i express --save$ touch index.js

copy the following code into index.js:

const express = require('express');const app = express();const PORT = process.env.PORTapp.get('/',(req,res) => { res.send("Hello World!\n");})app.listen(PORT,() => { console.log(`server is running on port ${PORT}`);})

Application Management

In order to run and manage our application with PM2, we need to configure it, first. PM2 configuration files can be in a variety of formats, including Javascript, JSON and YAML. We will be using a JSON file in this walk-through. Begin by running the following command:

$ pm2 ecosystem

This will automatically generate a config file for you by the name of ecosystem.config.js:

module.exports = { apps : [{ script: 'index.js', watch: '.' }, { script: './service-worker/', watch: ['./service-worker'] }],
deploy : { production : { user : 'SSH_USERNAME', host : 'SSH_HOSTMACHINE', ref : 'origin/master', repo : 'GIT_REPOSITORY', path : 'DESTINATION_PATH', 'pre-deploy-local': '', 'post-deploy' : 'npm install && pm2 reload ecosystem.config.js --env production', 'pre-setup': '' } }};

Make sure that this file is in the root of your application directory. As you can see above, PM2 is highly configurable, with many advanced options such as deployment hooks. For a detailed list of configuration choices, refer to the PM2 configuration docs

The only thing left to do is to add a new environment variable to configure the port on which the application shall run:

module.exports = { apps : [{ script: 'index.js', watch: '.', // add the port as an environment variable env: { PORT: 8080 } ...

Start the application with PM2 using the following command:

$ pm2 start ecosystem.config.js

After a few seconds, the application is live and listening for requests:

$ curl localhost:8080

Hello World!