Node.js as a Service on Linux

One of the problems using Node to run a server is that it is still a single, non-continuous process. This means if it crashes, it's gone. It will not restart itself.

There are several solutions available including forever, but they all involve installing needless packages and utilities. If there is one thing you will learn about me, it is that I hate installing a bunch of software for a simple problem. It seems today everyone looks for the first easy solution. But, that is a rant for another post.

Enter Upstart. It manages starting, stopping, and restarting processes based on system events. This utility is used by Fedora, Ubuntu, and other distros (including Amazon's Linux AMI) and comes pre-installed. If it doesn't, it's small and lightweight. We will use Upstart to automatically start our Node.js server on boot, stop it on shutdown, and restart it when it crashes.

In my case, I wanted to turn Ghost into a service for easy management on my EC2 instance.


Create a new config and save it with a .conf extension in the Upstart config directory (ex: /etc/init/ghost.conf). The name of the file will be the name of the service used for manual starting and stopping.

# Locations to log files
env ERROR_LOGFILE=/www/ghost/logs/ghost_error.log  
env ACCESS_LOGFILE=/www/ghost/logs/ghost_access.log  
env SYSTEM_LOGFILE=/www/ghost/logs/ghost_system.log

# Location to script that starts Ghost
env GHOST=/www/ghost/start


# Some basic info about the service
description "Ghost service"  
author      "Mike"


# Start the service on system start, stop on system shutdown
start on startup  
stop on shutdown

# If the process exists with a non 0 status code, restart the process
# Stop restarting the process if it has been restarted more than 3 times in 5 seconds
respawn  
respawn limit 3 5


# Process to run.
# Redirect stderr to our error log file and stdout to our access log file.
exec $GHOST 2>> $ERROR_LOGFILE 1>> $ACCESS_LOGFILE


# Log when we are starting our process to our system log file.
pre-start script  
    echo "Starting Ghost..."
    echo "[`date -u +%Y-%m-%dT%T.%3NZ`] Starting" >> $SYSTEM_LOGFILE
end script

# Log when we are stopping out process to our system log file.
pre-stop script  
    echo "Stopping Ghost..."
    echo "[`date -u +%Y-%m-%dT%T.%3NZ`] Stopping" >> $SYSTEM_LOGFILE
end script  



We can now also manually start and stop our service with:

start ghost
stop ghost

Replace ghost with the filename of your config without the .conf extension. If you get the error message Unknown job: ghost, this could mean that you did not create the config in the correct place, or there is a syntax error in your config. If you get Rejected send message, you may not have permission. Try sudo.