You ever had to restart your Node.js instances manually since it was crashed?
Well, I had. And maybe right now you are being stuck in the middle of the situation.
Server gets OOM (Out-of-Memory), it automatically kills Node.js. Runtime exceptions is very likely to kill your application, too.
Worst case, supposed it was in the middle of the night, 3AM for example, when you were continuously getting service-down notifications in your dreams. You’d wish, ‘Hope it could somehow automatically restart for me‘.
Using Forever to keep your app running
As its name describes, forever, will keep your Node.js apps running continuously as a service and it will automatically handle unexpected crashes for you.
Apart from automating the recovery tasks, it will start your server in the child process but a long running process so that your server will still living even though you close the Terminal/ Shell window.
Installing and start daemonizing
- You could install
forever globally using
1$ sudo npm install -g forever
- After installing, you can now run your node.js application by typing:
1$ forever index.js
In order to prevent this, we should run the application as a background service, by adding start into the command:1$ forever start index.js
forever restarts your application whenever it stops for whatever the reasons are. To limit the amount of times it restarts, use: -mX. 6 times for example:1$ forever start -m6 index.js
- To list all running applications:
1$ forever list
You will find something like this:1234$ forever listinfo: Forever processes runningdata: uid command script forever pid id logfile uptimedata:  H0Km /usr/bin/node index.js 9651 9653 /home/ghost/.forever/H0Km.log 0:5:57:21.261
The number in the  brackets is used for users (you) to take manual actions in forever.
- Stop a process by:
1$ forever stop 0
is the process id we took from the #3.
- To restart a running application, goes:
1$ forever restart 0
- If you are developing some scripts, use -w for automatic restarts when the file changes:
1$ forever -w index.js
Right now forever only supports Node.js applications. Maybe it will support other services like PHP or MySQL in the future, who knows?
But at this moment, we can tell that it can help keeping my & your Node.js server up and take away a lot of headaches.