Skip to content

Restart Node.js automatically

Anne Gentle edited this page Sep 13, 2015 · 7 revisions

If you are worried about lost connections to mongolabs or node crashing, configure your apps to run in an auto restart wrapper. You have some options, one is a tool called forever, the other is production process manager (pm2) to restart node if it crashes.

Here is how to implement forever: (**note some hosting services already use forever but in some cases they don't)


These steps where tested with Linux and Windows.
1. At the command prompt type: `sudo npm install forever -g`.
2. Once it is installed type: `forever start server.js`.
3. To see if it is running type: `forever list`.

The github respository for `forever` is: https://github.com/nodejitsu/forever.

There is also a production process manager for node called `pm2`. It can also
autorestart the server, gives more control and a web interface to see the status of node applications running on the server. 

Here is how to install and use pm2:
1. Type: `sudo npm install -g pm2`.
2. Change directories into the nightscout directory: `cd pm2`.
3. Type: `pm2 start server.js` to start the server app for cgm-remote-monitor,
   for example.
4. To see if the `server.js` app is running, use the web interface which is
   running on your webserver address on port 9615), or type: `pm2 status` in
   the command line for the server.

This process manager uses the `my.env` environment variables but it keeps them even after restarting the application, so use `pm2 describe server` to view the environment variables used at the start of `server.js`.

The github repository for `pm2` is https://github.com/Unitech/PM2.