Skip to content

Instantly share code, notes, and snippets.

@willrstern
Last active August 17, 2023 10:15
Show Gist options
  • Save willrstern/3510ecef59c3f76b0152 to your computer and use it in GitHub Desktop.
Save willrstern/3510ecef59c3f76b0152 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
@miclovich
Copy link

Is this working for Ubuntu 15.04 (and the systemd) for anyone else?

@jeveloper
Copy link

@miclovich Its very different , different commands and an extra step to make it boot up together with system so no i wouldn't recommend touching ubuntu 15.04 if you aren't ready for different system configuration. Also 15 is not an LTS version.

Here is a cheatsheet for SystemD
http://linoxide.com/linux-command/systemd-vs-sysvinit-cheatsheet/

@xolar
Copy link

xolar commented Mar 9, 2016

Cheers!

@matt212
Copy link

matt212 commented Mar 15, 2016

Hi,
I have below code in my app.js file
http.createServer(app).listen(config.port, config.address, function() {
console.log("Express server listening on %s:%d in %s mode", config.address, config.port, app.settings.env);
});
How can i allocated different ports from above script and run multiple instance on different ports

@joepie91
Copy link

This Gist is DANGEROUS.

If you use this Gist as-is, it will run your application as root, which is a serious security issue. You will want to use setuid to run it under a limited user (you can use the adduser command to create one), like demonstrated in this post.

@VLZH
Copy link

VLZH commented Jun 24, 2016

Thanks!)

@droidmanspace
Copy link

thanks

@aniqi
Copy link

aniqi commented Jan 25, 2018

perfectly!

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