Node JS auto restart all forever JS process when server goes down / crashes

Faizan picture Faizan · May 12, 2016 · Viewed 45.9k times · Source

I am using forever js to keep my node server running 24/7 on AWS EC2.

I use this command

forever start index.js

However, I notice that some time it randomly stops the process and my site goes down. I have to manually ssh into my server to run it again by doing:

forever restartall

And then it goes backup. Is there any way by which I can define a timeout, lets say if the server/website does not respond for 200 in 5 sec, then restart all forever process automatically?

I am new to this, if any one can give me step by step example for my case, it would be awesome.

Answer

boehm_s picture boehm_s · Jun 5, 2016

A (NodeJS) server should not stop for no reason. Most of the time, it's because of a 500 Error that have not been catched and stop the server, then you will have to restart it. forever is using node by default to start your server.

nodemon is a npm package that restart your server when the code changes or when your server stops.

You can use forever and nodemon together by doing :

forever start nodemon --exitcrash app.js

or

forever start -c nodemon app.js

Or, as suggested in other answers, you can use PM2, which would be better for production !