Experience on PM2 Tricks to manage your NodeJs processes

Geofrey Bundala
ClickPesa Engineering Blog

--

As a back-end developer, I always interact with the servers by using different tools in order to visualize ongoing and failed processes by checking logs also debugging, etc, when it comes to NodeJs PM2 is a common tool to be used

One day I was working on the server and I was changing only the environment variable to make changes to reflect I restarted an app by running the command

PM2 restart <App name>

It fails to restart due to an error of missing some environment variable, I was looking for a fast way around to start again an app again I took some time for fixing by adding those missing variables but I was not lucky at all

Then thanks to my team leader remind me to use

PM2 resurrect

And the app starts running :)

What is PM2

PM2 is node daemon process management that comes with a load balancer (improves application availability and responsiveness and prevents server overload).

PM2 offers a simple CLI tool and is installed via NPM, and a bunch of commands to be used on starting, stopping, restarting, checking logs, and more

What PM2 resurrect does it to restore previously saved process list

PM2 process lists are saved with the command below

PM2 save

PM2 save takes a snapshot of your currently running Node applications, This saves the processes currently managed by PM2 to disk so they’re accessible to the daemon on system boot.

Running PM2 contains the environment(process.env) variable on the heap (The heap is the RAM used by the program you’re asking PM2 to manage and monitor), saving command will save all instances variables

you can see what memory usage by this command.

pm2 monit

This means in case something went wrong resurrect can be used to revert running instances with no issue

Advantages of using PM2

  • pm2 offer to run multiple processes with multiple cores of CPU to achieve the Load Balancer like effect
  • Can easily be used on CI/CD deployment
  • Schedule to restart periodically
  • pm2 help to organize the log
  • Allows auto-restart under specific conditions, such as ‘up-time’, ‘memory usage’
  • It provides much information, including restarting number, CPU usage, memory usage, process_id, etc.

Alternative of PM2 with build-in load Balancer

Nodemon.io

Monitor for any changes in your node.js application and automatically restart the server — perfect for development

Forever

A simple CLI tool for ensuring that a given script runs continuously (i.e. forever)

Supervisor

Supervisor process control system for UNIX

You can add a comment below on the issue you faced on the servers

If you like this article there are more like this in our blogs, follow us on dev.to and medium

--

--