Search This Blog

Sunday, January 19, 2014

Run Node.js as a service on ubuntu

In this tutorial we will host a new node.js service on ubuntu linux using upstart.

Assuming you have a working node.js "Hello World!" kind of service.


var http = require("http");


var url  = require('url');




http.createServer(function(request, response) {


  response.write("Hello World!");


  response.end();


}).listen(8888);


This particular service listens to the port 8888.

http://localhost:8888

So now all we have to do left is make it run as a service [optional: and run on startup]

Install upstart



sudo apt-get install upstart

Cofigure your script



vi /etc/init/nodejs_server.conf
#!upstart
description "node.js server"
author "Rasta"

start on starting networking
stop on shutdown

script
export HOME="/home/USER_NAME"

echo $$ > /var/run/SERVICE_NAME.pid
exec sudo -u
USER_NAME /usr/bin/node ~/nodejs/server.js >> /var/log/nodejs_server.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" >> /var/log/nodejsserver.log
end script

Now let's go over this..
start on starting networking
stop on shutdown

upstart allows us to determine when the script will be activated.
We want the nodejs service to be up and running whenever the network is ready to be used,
and be shutdown along with the machine.

The script


script
export HOME="/home/USER_NAME"

echo $$ > /var/run/SERVICE_NAME.pid
exec sudo -u
USER_NAME PATH FILE.js >> /var/log/nodejs_server.log 2>&1
end script

Our variables:

  1. USER_NAME - the name of the user that will run the service
  2. SERVICE_NAME - will be displayed in your "ps" command
  3. PATH - is where the nodejs executables are , usually it's "/usr/bin/node" or "/usr/local/bin/node"
  4. FILE.js - is your hello world service. you need to use "~/path" to concatenate the file path to your HOME variable.
Pre-start script


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

Will just get you informed that the service is starting..

Manually start/stop

[sudo] /sbin/start nodejs_server
[sudo] /sbin/stop nodejs_server

Read the log

Read the log file to check for errors and Node.js's console.log command.
cat /var/log/nodejs_server.log