Forever is a useful tool for running a Node.js process with monitoring; it can be set to restart a failed process, and has a few other helpful features along the same lines. In this post you'll find a couple of exceedingly simple scripts for running a Node.js process as a service on Ubuntu using Forever.
One thing I've found in the course of building and tinkering with Node.js is that there's a lot to be said for explicitly setting all the necessary environment variables in your service script. That way the same basic script will serve just fine for locally built versus package manager installations of Node.js, and for code that moves from being a local development copy to a package installed via NPM. Just change the relevant environment variables in your service script as appropriate, and it will remain perfectly clear from the contents of the script as to the circumstances under which it will work. No more puzzling over whether the node binary is in PATH, or what NODE_PATH is set to when Forever forks its child process.
Install Forever Globally
Forever must be installed globally via NPM for the example scripts to work, such that its binary is in the same directory as the Node.js binary:
npm -g install forever
Upstart is an alternative to using standard issue init scripts and is installed by default on Ubuntu. A script resides in the /etc/init folder and has a .conf file extension, e.g. /etc/init/my-application.conf. Run or check on the script and its process with the following commands:
start my-application status my-application restart my-application stop my-application
Most upstart scripts are set to automatically start and stop for specific run levels in the same way as init scripts. Here is an example Upstart script for a Node.js service running under Forever:
Init scripts hopefully need no explanation. Scripts reside in /etc/init.d with root ownership and executable permissions. e.g.:
sudo su cp my-application-script /etc/init.d/my-application chmod a+x /etc/init.d/my-application
After putting the script in place, you should update the system service definitions:
update-rc.d my-application defaults
Run or check on the script and its process with the following commands:
service my-application start service my-application status service my-application restart service my-application stop
Here is an example init script for a Node.js service running under Forever: