Hey everyone, hope all is well.
Today I want to share with you a popular process managing tool called pm2 that can help you keep your Node.js projects alive 24/7.
This tool is mainly used on production servers, but given its awesome monitoring capabilities & advanced features, I love using it to monitor my projects in development for any unwanted behavior.
This post will be fairly basic & images screenshotted will use the sneaky-ninja-hive curation bot project running on my local machine as an example.
If you'd like to take a deep dive into how pm2 works & everything it can offer you, take a look at their document page
Installation:
Assuming that both Node.js & npm are installed, we can use npm for the installation.
sudo npm install pm2 -g
Starting / Stopping your project with pm2:
Change directory to your project, then using pm2 we can start it with
pm2 start projectName.js
By default, pm2 starts the project in daemonized mode, so you can close the terminal & the project will still be running in the background.
Pm2 will now automatically restart the project if it stops for any reason.
In the above image, we can see that our project was assigned an id of 0, using this we can stop the process if needed.
pm2 stop 0
then kill the daemon still running in the background
pm2 kill
If you use pm2 to monitor multiple projects/processes, pm2 kill
will stop all processes it's managing!
Monitoring:
1.Local:
Monitoring is one of pm2's best features & comes with a few fun ways that you can keep track of your projects.
To monitor your projects, simply type
pm2 monit
From this monitoring screen, we can get a lot of useful information like how many active requests, CPU usage, memory usage, etc...
Ctrl + C or closing the terminal will not stop the processes.
2.Keymetrics
With keymetrics we can monitor our projects via their web page
In order for this to work, you will need to link your current project to keymetrics. After signing up for the site they will provide you with 2 keys.
If you are currently in the active directory of your project, you can link it with
pm2 link xxkey1xxx xxkey2xx
Boom! You are now set up to monitor your project(s) from anywhere in the world.