Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Deploy Node.js app on Ubuntu as Upstart Service - instead of using Forever

Deploying a node app with Forever is great...until your server restarts unexpectedly. Then your app stops running and you have to re-deploy.

To get around this, we're going to run our node app as an Upstart service. Upstart services are great, because, once started, the system auto-restarts them if they fail, or if the server restarts.

###Step 1: Create a service for your node app

  • ssh in as root ssh root@youripaddress
  • Create a node-app.conf file in /etc/init
    IMPORTANT: whatever filename you pick is what you will use to start|stop|restart your service i.e. service node-app start
nano /etc/init/node-app.conf
  • Give the file the following contents
start on filesystem and started networking
respawn
chdir /home/deploy/node-app
env NODE_ENV=production #change this to staging if this is a staging server
env PORT=3000
exec /usr/local/bin/node bin/www
  • Now your app will always start on reboot!
  • You can also now you can start | stop | restart your app with these commands
start node-app
stop node-app
restart node-app #performs a stop and start. This is all we need for deployments

###Step 2: give your deploy user permission to restart the node-app service without requiring a password You can make changes to this entry later by running visudo as root, but for now, just run this.

echo "deploy ALL=(root) NOPASSWD: /sbin/restart node-app" >> /etc/sudoers

###Step 3: Adjust your flightplan.js file - remove the forever lines, replacing them with the last line here View full file, minus these changes here

remote.log('Reload application');
remote.sudo('ln -snf ~/' + tmpDir + ' ~/'+appName, {user: username});
remote.exec('sudo restart node-app');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment