Skip to content

Instantly share code, notes, and snippets.

@louischatriot
Created August 18, 2012 07:47
Show Gist options
  • Save louischatriot/3385102 to your computer and use it in GitHub Desktop.
Save louischatriot/3385102 to your computer and use it in GitHub Desktop.
Upstart script to launch a nodejs application as a service
description "Upstart script to run a nodejs app as a service"
author "Louis Chatriot"
env NODE_BIN=/usr/local/bin/node
env APP_DIR=/path/to/app/dir
env SCRIPT_FILE="scriptfile.js" # Entry point for the nodejs app
env LOG_FILE=/path/to/logfile.log
env RUN_AS="anyuser" # Upstart can only be run nicely as root, need to drop privileges
env SERVER_ENV="anything" # Usual apps can be run in different environments (development, test, production ...)
# I typically use the environment variable NODE_ENV (see below)
# If not needed simply remove the "NODE_ENV=$SERVER_ENV" below
# Start service on startup, stop on shutdown
start on runlevel [2345]
stop on runlevel [016]
# Respawn in case of a crash, with default parameters
respawn
script
# Make sure logfile exists and can be written by the user we drop privileges to
touch $LOG_FILE
chown $RUN_AS:$RUN_AS $LOG_FILE
chdir $APP_DIR
NODE_ENV=$SERVER_ENV su -s /bin/sh -c 'exec "$0" "$@"' $RUN_AS -- $NODE_BIN $SCRIPT_FILE >> $LOG_FILE 2>&1
end script
post-start script
echo "===== App restarted =====" >> $LOG_FILE
end script
@louischatriot
Copy link
Author

Pretty simple Upstart script (as with all Upstart scripts) we use to run our different nodejs applications as a service. Note that the privilege drop cannot be achieved with a sudo -u within an Upstart script (I don't remember the reason). Moreover, future versions of Upstart will support running a service directly as a specific user.

@m1keil
Copy link

m1keil commented May 2, 2013

thank you

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