I'm not sure what it is about startup scripts, but people seem intent on complicating them. In my experience the simplest way to keep a non-daemonizing NodeJS app running (on an Ubuntu server) is to use Upstart. Upstart has sensible behaviour and defaults that make it perfect for network services like a NodeJS app.
Here's my example script, which would belong in /etc/init/my-nodejs-server.conf
description "My NodeJS Server"
author "John Appleseed"
env PORT=5001
start on runlevel [2345]
stop on runlevel [016]
respawn
setuid john
chdir /home/john/Applications/my-nodejs-server/
exec node index.js
With this file in place (that's all you need to do!) you could sudo service my-nodejs-server start
and it'd be up and running. With this 9 line script we have some powerful configuration already:
- We can configure environment variables in a faux 12 factor style.
- Our NodeJS app will automatically start on boot, and stop on shutdown.
- Upstart will restart the app if it crashes.
- It will run as our unpriveleged user 'john'.
- Upstart (1.4 and above) will log all output to
/var/log/upstart/my-nodejs-server.log
which will be rotated by logrotate. - We can manage the lifecycle with
sudo service my-nodejs-server {start,stop,restart}
. - We can temporarily disable the app from starting on boot with an override file:
$ echo manual | sudo tee /etc/init/my-nodejs-server.override
.
That's a lot of functionality for a 9 line script, and we didn't even need to use a third party NodeJS library like Forever (though you could add that, but I'm not sure why) or make our app daemonize. Upstart also has a massive amount of functionality in some reasonably clear documentation; there's a lot more you can do with it.
So next time you see a 250+ line init.d script for a NodeJS app, remember there is a better way.