DEV Community

Cover image for Experience on PM2 Tricks to manage your NodeJs processes
Geofrey Bundala for ClickPesa

Posted on

Experience on PM2 Tricks to manage your NodeJs processes

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

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

PM2 restart <App name>

It fails to restart due to error of missing some environment variable , I was looking fast way around to start again an app again I took some time for fixing by adding those missing variable but I was not luck 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 load balancer (improves application availability and responsiveness and prevents server overload).
PM2 offers a simple CLI tool and is installed via NPM , and bunch of command to be used on starting, stoping, restarting, checking logs and more

What PM2 resurrect does it to restore previously saved process list
PM2 process list are saved with 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 environment(process.env) variable on 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 incase something went wrong resurrect can be used to revert running instances with no issue

Advantage of using PM2

pm2 offer run multiple processes with multiple cores of CPU to achieve the Load Balancer like effect
Can easy used on CI/CD deployment
Schedule to restart periodically
pm2 help to organise 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 NodeJS 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 comment below on the issue you faced on servers

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

Top comments (0)