Node.js Automatic Restart After a Crash
Node.js Auto Restart After Crash
I run a couple different Node.js applications that relate to my Capstone Project. Which specifically involves a data collection aspect, which runs on a virtual machine 24/7. Since it is meant to always be running, I don’t monitor it all the time.
However, I recently ran into an issue where one of the Node.js application stopped running unexpectedly. I was not aware of it, so I lost the opportunity to capture data temporarily until I was able to manually restart it.
This was definitely not ideal, so it posed the question: How do I make it automatically restart after an unexpected crash?
What I Used to Use
Before this occured, I utilized Nodemon which is a great tool for automatically restarting a Node.js application when files in the same directory are changed.
This is a very useful tool when used during the development of the Node.js applications. But since I am rarely updating the specific data collection application anymore, and only having it run 24/7, it is no longer ideal for my circumstances.
What I Use Now
Since Nodemon was not able to handle my specific circumstances in this instance, I looked around and eventually found another npm package called pm2.
Based on the description listed on the packages page, it looked like something that could potentially meet my need for automatically restarting itself after unexpected crashes.
To install pm2, I ran this:
npm install pm2 -g
Then to start my Node.js application, I simply went to the directory of my file and ran this:
pm2 start app.js
After I ran the above snippet, it displayed this:

Indicating that it is now running my Node.js application in pm2, and monitoring it for any issues.
I also was able to use this to list what I had running in pm2:
pm2 ls

It has been running fine for several hours already, and I will continue to occasionally monitor it to make sure that it is handling any unexpected crashes as needed.