Deploying node.js app using upstart

upstart is a new service manager that replacing old init.d in newer linux. In newer ubuntu, it is preinstalled. Otherwise you can installed in default package.

To deploy node.js app using upstart, create a script (e.g. node-your-app-name.conf) in /etc/init

description     "Your app description"
author "John Doe"

start on runlevel [2345]
stop on runlevel [!2345]
# setuid only avaiable after upstart 1.4, please check your version first
setuid ubuntu

env NODE=/usr/bin/node
env NODE_APP_PATH=/var/www/node-blog
env LOG_FILE=/var/log/nodejs/node-blog.log
env NODE_ENV=production
env PORT=8105

# you can remove this if you don't want to pull from git before start the service
pre-start script
  git pull origin master >> $LOG_FILE 2>&1
end script

  $NODE lib/app.js >> $LOG_FILE 2>&1
end script

The script will:

  • set as production environment.
  • set the owner of the service, so no need to run as root.
  • set the port if the node.js app. It's useful for express.js deployment.
  • make a pull before start the app. You can remove it if you don't want to.
  • respawn if the node crashed. So there is no need to monitor the health of the mode using other method like foreverd.

Now, the app will auto start when the server restart, or you can start service manually:

sudo service node-your-app-name start

Also, you can stop or restart the service using:

sudo service node-your-app-name stop

sudo service node-your-app-name restart