Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save roninhack/6fd05d6b0b878422d1ac2817a96e8522 to your computer and use it in GitHub Desktop.

Select an option

Save roninhack/6fd05d6b0b878422d1ac2817a96e8522 to your computer and use it in GitHub Desktop.
Run Node.js App as Ubuntu Upstart Service

###The Issue With Forever Forever is great for running node services, with a minor setback: the word "forever" doesn't apply to system reboots.

###The solution, run node apps as a system service logged in as root

vim /etc/init/node-app.conf

Contents for node-app.conf

start on filesystem and started networking
respawn
chdir /home/deploy/node-app  #deployment directory
env NODE_ENV=production
env PORT=3000
exec /usr/local/bin/node server/cluster.js  #start command - no forever needed, if it fails, the service restarts

SUCCESS! Now the app runs on reboot! You can also control the app as a service

service node-app start #node-app is filename of service.conf file
service node-app stop
service node-app restart #run this one command on deploy to either start | restart the service

###So how does my deploy script change? Run visudo to give deploy user permission to run only the node service without a password

echo "deploy ALL=(root) NOPASSWD: /sbin/restart node-app" >> /etc/sudoers
#this can be edited later by running visudo as root user

Now, run this with your deploy script as your deploy user

sudo restart node-app

Ubuntu 15.04 and Above Fix

Ubuntu switched to systemd as its service framework starting in 15.04 for all flavors, including Desktop and Server. The recommended practice is to change your upstart jobs to systemd jobs (see the wiki article for more info). You can also switch back to upstart if you want, which is certainly the quicker fix. I recommend you read the first few sections of the wiki article to weight the pros and cons.

Recommended Fix

Refer to the wiki article to transition your upstart scripts to systemd.

Discussion and coding guide: Systemd For Upstart Users

Quick Fix

To permanently switch back to upstart just run:

sudo apt-get install upstart-sysv sudo update-initramfs -u sudo reboot

EDIT: The wiki article only recommends this for 15.04 and above; don't do this on other versions! Thanks for TheSchwa from Stackoverflow.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment