I've ended up here more than once so I thought I'd provide an updated answer based on my own experience after using the answers here. Thanks especially to @danorton and @orj for their answers.
This script has been tested on Upstart 1.5 running on Ubuntu 12.04 with Nginx 1.0.11 and Passenger 3.0.11. If you're not using Passenger you may need to play around with the post-stop
line. Refer to the Upstart cookbook.
In an empty /etc/init/nginx.conf
add the following lines (You can remove the comments if you like):
description "nginx http daemon"
start on (filesystem and net-device-up IFACE=lo)
stop on runlevel [!2345]
env DAEMON=/usr/local/nginx/sbin/nginx
env PIDFILE=/var/run/nginx.pid
# Needed to allow Nginx to start, however, the wrong PID will be tracked
expect fork
# Test the nginx configuration (Upstart will not proceed if this fails)
pre-start exec $DAEMON -t
# Ensure nginx is shutdown gracefully
# Upstart will be tracking the wrong PID so the following is needed to stop nginx
post-stop exec start-stop-daemon --stop --pidfile $PIDFILE --name nginx --exec $DAEMON --signal QUIT
# Start Nginx
exec $DAEMON
I've taken the Upstart script from the Nginx Wiki and tweaked it as a number of lines are not needed, cause confusion or do not work.
You may need to alter env DAEMON
and env PID
lines depending on where you have installed nginx and are writing the PID. The PID can be configured in nginx.
I tried all forms of expect
. Only expect fork
seems to work. With Passenger nginx creates 61 forks. Upstart requires 0, 1 or 2. As others have hinted, Upstart will be tracking the wrong PID. I've also removed respawn
as it does nothing probably because of the same reason. Some additional pre/post-start script may be able to fix that by grabbing the real PID. I, however, use monit to handle restarts so do not need it.
Do not use daemon off
. This is for development only. See http://wiki.nginx.org/CoreModule#daemon
References: