How to Setup a Node.js Application Using PM2

What is PM2?

PM2 (http://pm2.keymetrics.io/) is a command-line utility that simplifies many of the tasks associated with running Node applications, monitoring their status, and efficiently scaling them to meet increasing demand.

PM2 can be used to instrument deployment and monitoring of your Node processes, both via the command line and programmatically. PM2 spares the developer the complexity of configuring clustering boilerplate, handles restarts automatically, and provides advanced logging and monitoring tools out of the box.

Installation

Step 1 : PM2’s command-line utility, pm2, is available via npm.

sudo npm install -g pm2

Step 2 : Test PM2

pm2 --version

Working with Processes

Step 1 : Now, let’s create a simple Node application. When accessed, it does nothing more than display the message “Hello, world. ” to users.

mkdir my-app
cd my-app/
nano index.js

Next, copy and paste the following pieces of code in the index.js files

// my-app/index.js

var express = require('express');
var morgan = require('morgan');
var app = express();
app.use(morgan('combined'));

app.get('/', function(req, res, next) {
    res.send('Hello, world.\n');
});

app.listen(8000);

Install the project’s dependencies

npm install express morgan

Step 2 : In this example, we instruct PM2 to start our application by executing its index.js script.

pm2 start index.js --name my-app 

We also provide PM2 with an (optional) name for our application (my-app), making it easier for us to reference it at a later time.

Step 3 : We can verify this by calling our application’s sole route using the curl command-line utility

curl localhost:8000 

PM2 offers straightforward commands : list, show, stop, start, restart, delete

Step 4 : List all processes

pm2 list 

Step 5 : Describe all parameters of a process

pm2 show my-app 

pm2 restart my-app 

Step 7 : Stop a process

pm2 stop my-app 

Step 8 : stop and delete a process from pm2 process list

pm2 delete my-app 

Add Comment