Nodejs monitoring

Nodejs monitoring using PM2

Nodejs monitoring in production server is very important and critical part in overall Nodejs application development. Unlike staging or development scenario, if anything goes wrong in production server it directly affects the end-user and most importantly your client. In this tutorial we will look over how to properly monitor our Nodejs server after deploying it to production using PM2 node module and keymetrics as analysis platform.

What is PM2

PM2 is a process manager for Nodejs application. It comes up with its own load balancer. It make sure that your Nodejs application is fully available to end-user by reloading them in case of exception.

Installing PM2

Installing PM2 is easy and you can do this by using following command.

npm install -g pm2@latest

PM2 should be installed as a global node module so that’s what -g will do. You may need to pass sudo access to it in case you are using Mac or Linux-based system.

Integrating PM2 with Nodejs

Before doing the integration let’s create one basic Node.js app using Express.

Use npm init to create a package.json.

package.json
{
  "name": "pm2demo",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Let’s install Express module. Run following command.

npm install --save express

Let’s create a basic server and integrate pm2 with it.

app.js
var express = require('express');
var app = express();
var router = express.Router();

router.get('/',function(req,res) {
    res.send("Hello World");
});

app.use('/',router);

app.listen(3000);

In order to run this app, we generally using npm or node command. But instead we are going to run this using PM2. Here is a command to do so.

pm2 start app.js

PM2 application server monitoring

You can run following command to check the status of the app every time.

pm2 status

Visit localhost:300 to view the app.

Now if your app crashes due to any issue, PM2 will restart it automatically. In order to stop the app you can run following command.

pm2 stop <app name> OR <app id>

In order to stop all process at once, run following command.

pm2 stop all

To stop the PM2 itself, run following command.

pm2 kill

To monitor the process live, run following command.

pm2 monit

PM2 monitor

This feed will update live as your application keeps running and used.

Integrating PM2 with Keymetrics

Keymetrics is a web platform to monitor your application using PM2. We just had a look above about monitor command in PM2. How about having that live information in your browser ? Pretty amazing to me. Go checkout keymetrics and sign up for new account.

Once you sign up, create a new Bucket.

Node.js monitoring

After this, Keymetrics will provide you the URL by which you can link your app to Keymetrics.

Keymetrics account

Just copy the command and paste it in your terminal.

Linking PM2 app

This is it, within a second you can see the live update of your application in your browser.

Nodejs monitoring using keymetrics

Keymetrics provides various features and admin option which you can use to perform Nodejs monitoring. Let’s have a look over some of them.

CPU and Memory usage

In the main dashboard you can see and visualize the amount of memory and CPU your app is consuming. This data is also live and you can see the comparative graph as well.

Nodejs monitoring using PM2

Exception reporting

This is one of the coolest part which i personally like more. In case your application crashes due to some exception, PM2 will report it to keymetrics and keymetrics will immediately send email to your account and will show the exception detail in dashboard.

In order to replicate it, let’s put some exception in our code. For some reason, throwing an exception is not working so I am going to put one syntax error. In our route code place extra comma like this.

router.get('/',,function(req,res) {
    res.send("Hello World");
});

Now restart the app using following command.

pm2 restart app.js

Hit the route using by visiting localhost:3000 and you should receive an email immediately like this.

Nodejs monitoring using PM2

Also you can see the exception in dashboard.

Nodejs monitoring using PM2

Other than Syntax error, it also catches exception which are dynamic such as call stack size exceeded which we discovered in different application.

Nodejs monitoring using PM2

Monitoring custom events

Other than exception, you can also register for custom events such as “10000 user registered” or anything suitable to your app. You need to install add-on for called pmx in order to emit custom event. Install it using following command.

npm install --save pmx

Then require it in your code and emit the events like this.

var pmx = require('pmx');

pmx.emit("Event name","event detail,supports JSON too");

Wrapping it up

PM2 and Keymetrics together is great tool for Nodejs monitoring in production server. Other than a fact that it keeps your application alive, it also keeps checking for exception and memory, CPU usage. You can also monitor logs in your browser and can restart your application as well.

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

7 Comments

  1. i ran into a problem where during server shutdown, all my pm2 jobs were being lost. the only workaround i could come up with is to go into this file:

    /etc/rc.d/init.d/pm2-init.sh

    and comment out this line:
    stop() {
    echo “Stopping $NAME”
    ##super $PM2 dump ## commented out

    the problem seemed to happen pretty randomly. i also made a permanent copy of this file:
    /root/.pm2/dump.pm2

    i am tempted to change the protection on it, and only open it up when i specifically choose to save my pm2 jobs.

    NOTE: pm2 can run any tasks, not just node stuff. i have a java script and a php script controlled by pm2. i am thinking its probably better to use pm2 than it is to use systemctl or service. opinions?

    1. I forgot to add section of “pm2 in restart”, i will as soon as i get time. Regarding using it as replacement of service or systemctl, i’d rather say it will be too soon for it. I mean PM2 is great but not mature enough yet. We can surely use it in projects but if any problem comes up, better to have backup like service or systemctl.

      1. >>> I mean PM2 is great but not mature enough yet.

        Maturity is so overrated. I have been immature my entire life and that has served me well.

        I agree on mysql(mariadb), ftp, apache, etc, but i am thinking that if pm2 is good enough for node stuff, its good enough for a lot more.

        i am running red5 server. it currently starts at bootup in rc.local, but i am going to let pm2 manage it for me.

    1. >>>> Can you please provide Server details ?
      Linux xxxxx.info 3.10.0-327.13.1.el7.x86_64 #1 SMP Thu Mar 31 16:04:38 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

      pm2 looks very promising for sure, especially looking at keymetrics web interface. once i am done wit the conversion, i will try pm2 again.

      my immediate guess is that this issue will disappear once pm2 is reinstalled from scratch.

Leave a Reply

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