Use an upstart script to run a NodeJS script as a service/daemon

Run Node as service in Linux

You will need an upstart or init script. I recommend upstart as it's the default in Ubuntu and much easier then an init script. Here's the script I use for my daemons:

#!upstart
description "Some useful info for your colleagues or future self"
author      "Your name"

#
# Copy this script to /etc/init/
# Don't forget to create a new user
#


# set a variable which is the name of a file this job will use
# to pass information between script sections.

env NAME="myNodeScript"

# make the variable accessible to all script sections (ie sub-shells)
export NAME

# Dependencies
start on startup or started nginx
stop on shutdown or stopping nginx

respawn


script
	export HOME="/tank/nodejs/$NAME"

	echo $$ > /var/run/$NAME.pid
	exec sudo -u $NAME /usr/bin/nodejs /tank/nodejs/$NAME/$NAME.js 2>&1 >>/tank/logs/log/nodejs/$NAME.log | tee -a /tank/logs/log/nodejs/$NAME.log | mail info@joha.nz -s $NAME
	
	#exec sudo -u $NAME /usr/bin/nodejs /tank/nodejs/$NAME/$NAME.js >> /tank/logs/log/nodejs/$NAME.log 2>&1
end script

pre-start script
	# Date format same as (new Date()).toISOString() for consistency
	echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Starting" >> /tank/logs/log/nodejs/$NAME.log
end script

pre-stop script
	rm /var/run/$NAME.pid
	echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Stopping" >> /tank/logs/log/nodejs/$NAME.log
end script

Make sure you replace /tank/nodejs/ with the path to Your Node.JS script. /tank/logs/log/nodejs/ to where you want the log files to go. And info@joha.nz to your own e-mail address. Or use the line below it if you do not want to have errors mailed to you.

You should create a new user, with the same name as the script:

useradd myNodeScript

And give it read and write access where needed. Or add the user to a group that has the rights needed.

You can now start, stop or restart the daemon just like any other service!

sudo service myNodeScript restart
sudo service myNodeScript stop
sudo service myNodeScript start


Written by Johan Zetterberg April 17th 2015.


Follow me via RSS:   RSS https://z├Ąta.com/rss_en.xml (copy to feed-reader)
or Github:   Github https://github.com/Z3TA