PM 2 : A quick-start guide

Varun Guleria
4 min readJun 6, 2018

--

Process Manager 2

If you are from NodeJS background, you must be aware about forever, nodemon, supervisord or systemd. All these libraries prevents crashing of NodeJS server in case there is some error/exception.

Let’s understand this with an example where we will simply create a Node JS server and throw an exception.

Index.jsvar express = require(‘express’);var app = express();app.listen(5500);app.get(‘/’, (req, res) => {
res.send(“Hello World”);
});
app.get(‘/exec’, (req, res) => { throw new Error(“Exception Occurred”); res.send(“Hi”);});

Now save, run the file by:

node index.js

and launch the browser with your IP:5500/exec. On console you will get:

throw new Error("Exception Occurred");^
Error: exc
at Server.app.listen (/home/varunguleria/WORK/****/src/gui/MYSTUDY/testPM2/index.js:7:9)
at Object.onceWrapper (events.js:314:30)
at emitNone (events.js:105:13)
at Server.emit (events.js:207:7)

Try to hit IP:5500/ on your browser, you will see error message as This site cannot be reached.

Do you know what happened????
Your server just CRASHED….

You don’t want your server to be crash by some silly exceptions while in production. To prevent such situations, we have many choices of libraries : forever, nodemon, supervisord or systemd. One of these libraries is PM2.

From Wiki :

“ PM2 is a process manager for the JavaScript runtime Node.js. In 2016, PM2 is ranked as the 82nd most popular JavaScript project on GitHub.

PM2 or Process Manager 2, is an Open Source, production Node.js process manager helping Developers and Devops manage Node.js applications in production environment. In comparison with other process manager like Supervisord, Forever, Systemd, some key features of PM2 are automatic application load balancing, declarative application configuration, deployment system and monitoring.”

Or in simple words,

PM2 is a process manager which restarts your server again in case there is some error/exception. It also distributes load in case one of your process is using CPU.

To install PM2,

npm install pm2@latest

Now to start your application with PM2, type:

pm2 start index.js

Lets try running above example with PM2 by typing:

pm2 start index.js

and in browser hit IP:5500/exec, you will get error on console.

But is your server still alive???

To check this, hit the browser with IP:5500/ and you will see that server is still running even after exception was occurred. Only your API IP:5500/exec is causing exception, rest your application is running fine.

Second use of PM2 is that it distributes load in case one of the process is taking up the CPU and halting other processes.

Let us understand this by running our example without PM2.

Without PM2

We will create an API which will have some CPU intensive task and other API which will just send response to client. We will then try to hit CPU Intensive API on one tab of browser and other API on another tab.

Index.jsvar express = require(‘express’);
var app = express();
app.listen(5500);
// API with simple response
app.get(‘/’, (req, res) => {
res.send(“Hello World”);
})
// API with CPU intensive task
app.get(‘/exec’, (req, res) => {
let n = 1200;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
console.log(`Iter ${i}.${j}`);
}
}
res.send(“Hi”);
});

Now save, run above program by typing:

node index.js

and on browser just type and don’t press enter IP:5500/exec on one tab and IP:5500/ on another tab. Now hit the IP on first tab and immediately hit the IP on another tab. You will notice that the IP on second tab I.e IP:5500/ will wait until the IP on first tab I.e IP:5500/exec completes its execution.

This happens because Nodejs is single threaded language and in our program you are trying to block that only thread by running number of iterations which in turn is blocking other waiting process.

To resolve this issue, run your node in cluster mode.

Cluster mode allows networked Node.js applications (http(s)/tcp/udp server) to be scaled accross all CPUs available, without any code modifications. This greatly increases the performance and reliability of your applications, depending on the number of CPUs available. Under the hood, this uses the Node.js cluster module such that the scaled application’s child processes can automatically share server ports.

pm2 start app.js -i max

max means that PM2 will auto detect the number of available CPUs and run as many processes as possible

With PM2

Lets try to implement this with last example:

pm2 start index.js -i 3

Now again perform the same steps again. On tab 1, type IP:5500/exec and on tab 2, type IP:5500/ .

Now hit IP on tab 1 and immediately hit the IP on tab 2. You will notice that even tab 1 is still processing the request but tab2 without waiting for Tab 1 to complete its execution ,has served you the response.

To see this list of pm2 processes:

pm2 list

To see logs:

Pm2 logs

To kill Node server

Pm2 delete all

To see list of all PM2 commands, head to the official site:

That’s all for now. Thanks for reading :)

--

--