Running your Node.js application as a system service on Linux with Upstart

I recently went through an exercise of deploying a Node.js application on Linux (Ubuntu 14.04) and I would like to share this tip with anyone who may require an information on how to run a Node.js application as a service on Linux OS, so the application will run normally when user exits the SSH console. There are many ways this can be achieved with applications like pm2, forever or nohup, but this post will focus on Upstart.

Upstart is an event-based replacement for the /sbin/init daemon which handles starting of tasks and services during boot, stopping them during shutdown and supervising them while the system is running.

I found it the most suitable way of setting up a Node.js application as a service on Linux also in production-like environments.

My application can be run by executing npm start --production on Windows, and I needed to find out how to make run it as a service on Linux.

I used nano (sudo nano /etc/init/myapp.conf) to create the following Upstart script:

description "A job running a Node.js application XYZ"  
author "John Doe"

start on filesystem or runlevel [2345]  
stop on shutdown

env NODE_ENV=production

script  
    export HOME="/var/www/myapp"
    echo $$ > /var/run/myapp.pid
    exec /opt/node/bin/node /var/www/myapp/index.js
end script

pre-start script  
    echo "[`date`] Application XYZ starting" >> /var/log/myapp.log
end script

pre-stop script  
    rm /var/run/myapp.pid
    echo "[`date`] Application XYZ stopping" >> /var/log/myapp.log
end script  

A few notes on particular statements - we do instruct to start this service when file system is available or OS boots to runlevel 2,3,4 or 5 - which means it is in operational mode - different than halt, maitenance mode or reboot. We also set the Node.js environment to "production" with env NODE_ENV=production. Each Upstart job gets a process id, we write this process id to file with echo $$ > /var/run/myapp.pid.

After saving this script, you can use service command to start/stop/restart your Node.js application easily. Example commands are:sudo service myapp stop, sudo service myapp start, sudo service myapp restart.

Comments

comments powered by Disqus