Ubuntu Upstart script with multiple daemons

Posted: June 19, 2011

Motivation

  • You have a service that needs to start more than one process
  • You want to use Ubuntu Upstart to manage the service
  • You want to su to another user when running the service

Example

description "my service name here"
version "1.0"
author "James Cooper"

env PATH=/bin:/usr/bin:/usr/local/bin
env RUNUSER=web
env LOGDIR=/home/$RUNUSER/logs

respawn
start on runlevel [23]

script
  mkdir -p $LOGDIR
  chown $RUNUSER $LOGDIR
  su $RUNUSER -c "/path/to/script1 & echo \$! > $LOGDIR/script1.pid"
  exec su $RUNUSER -c "exec /path/to/script2 >> $LOGDIR/stdout.log 2>> $LOGDIR/stderr.log"
end script

pre-stop exec kill `cat $LOGDIR/logs/script1.pid`

Notes

  • The pre-stop hook runs first when you stop the service. It kills script1
  • Make sure you backslash escape the $!
  • No ; after the & that backgrounds script1