I recently moved a handful of my personal projects from Heroku to Digital Ocean. Partly I did this because the terms of Heroku's free tier changed, but mostly because I've wanted more control over the server and experience managing a server for a while.
The projects I moved were all written in node and I needed a way to start them up when the server started, and keep them up if they ever died. And hey, since Upstart handles log rotation too, all the better.
I can't be the only person to want to run a node app with Upstart, so I started looking around. What I found was a bunch of Upstart configurations that used scripts instead of the native features of Upstart. I thought there had to be a better way.
So I dug into the docs. Here's what I came up with.
description "burgers.io node application"
author "Bryan Burgers <firstname.lastname@example.org>"
start on started networking
stop on stopping networking
respawn limit 10 60
exec /usr/bin/node /var/apps/burgers.io/current/index.js
burgers.io is a node app, in case you didn't know. I didn't let anybody else write it, either.
If you're familiar with deploying to Heroku or have read 12factor.net/config, this won't come as a surprise. All configuration for the site is set in environment variables. So, we need to set those values in the upstart config.
Most node apps expect the current working directory to be the root of the application. Let's oblige.
Principle of Least Privilege here. Run the app as the user named burgersio rather root.
Don't start the application until the network services have loaded. Let me admit what I don't know: I don't know what I should be waiting for here. But this seems to work.
Restart if the node app ever dies. Which node apps do from time to time. But if it does more than 10 times in 60 seconds, just cool it for a bit.
That's it, run it!
There's nothing crazy here. Upstart has more than enough features to successfully run a node app.