Make your server process run forever

You may have written a fancy server in Node.js, Python, or Ruby, and now you're wondering how to keep the server running forever.

There are many possible choices when it comes to selecting a process daemon tool, like daemontools, supervisor, nagios, and forever.

However, if you are using Ubuntu on your production machine, it's very convenient to use the built in daemon tool. Any newer Ubuntu server comes with the "Upstart" init-daemon, which is used to start, monitor, stop and restart OS processes.

Even the best code have bugs. So, your server may exit unexpectedly at any time, and needs to be restarted. This is a job for Upstart.

All you need do is create a configuration file for your server in /etc/init.

Here is an example configuration file:

start on (local-filesystems and net-device-up IFACE!=lo)
stop on runlevel [!2345]

chdir /home/server
setuid www

exec 2>&1 1>>/var/log/server.log

respawn limit 5 10

This configuration make the www user run the shell script located in /home/server.

All output from the server is redirected to a log file.

If the server process crashes, Upstart will restart (respawn) the process. Though, if the process crashes more than 5 times within 10 seconds, it will bail out and not restart the server again.

Let's assume you've saved the config file as /etc/init/myserver.conf — then you can start the server with the command:

start myserver

(Use sudo if you're not logged in as root.)

Your server will be started automatically at boot time, and restarted if the process crash.

This introduction should be sufficient for you to get started using Upstart to keep your server processes running.

Upstart can do a lot more than what I've covered here, like waiting to start your server until some other process has started, e.g., the database.

You can get all the insights in the Upstart Intro, Cookbok and Best Practises document.