This blog is running WordPress on Nginx on a 256 slice from Slicehost. I’ve diligently followed all of the awesome articles by Slicehost’s tutorial master, Pickled Onion. And I even googled some other great stuff. But when it came down to PHP, spawn-fcgi, and particularly the Ubuntu way of daemon initialization, I had to blaze a new trail.
Here is the spawn-fcgi-php
script that I came up with:
#! /bin/sh ### BEGIN INIT INFO # Provides: spawn-fcgi-php # Required-Start: $all # Required-Stop: $all # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: starts FastCGI for PHP # Description: starts FastCGI for PHP using start-stop-daemon ### END INIT INFO PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin NAME=spawn-fcgi-php PID=/var/run/spawn-fcgi-php.pid DAEMON=/usr/local/bin/spawn-fcgi DAEMON_OPTS="-f /usr/bin/php-cgi -a 127.0.0.1 -p 55155 -u www-data -g www-data -P $PID" test -x $DAEMON || exit 0 set -e case "$1" in start) echo "Starting $NAME: " start-stop-daemon --start --pidfile $PID --exec $DAEMON -- $DAEMON_OPTS echo "done." ;; stop) echo "Stopping $NAME: " start-stop-daemon --stop --pidfile $PID --retry 5 rm -f $PID echo "done." ;; restart) echo "Stopping $NAME: " start-stop-daemon --stop --pidfile $PID --retry 5 rm -f $PID echo "done..." sleep 1 echo "Starting $NAME: " start-stop-daemon --start --pidfile $PID --exec $DAEMON -- $DAEMON_OPTS echo "done." ;; *) echo "Usage: /etc/init.d/$NAME {start|stop|restart}" >&2 exit 1 ;; esac exit 0
A pretty straight forward script the does just two things: start
and stop
. The restart
is just a convenience option, composed of a stop
plus a start
with a sleep 1
in between.
start
The script starts spawn-fcgi
from lightty with a couple of options, most importantly a port and a pid-file. By default, spawn-fcgi
will start up 5 child instances of php-cgi
. So a quick ps aux | grep cgi
will show 6 processes. From the limited (aka non-existent) performance data of my blog, this seems like a fine number.
stop
The script stops all those instances by sending a SIGTERM (-15) to the parent process recorded in the pid-file. Stopping with the --retry 5
option, will first send the default SIGTERM signal and check for 5 seconds if the process is still running, then send a KILL (-9) signal and wait another 5 seconds before erroring out.
Digging Deeper: When stopping, pass only one matching option to the
start-stop-daemon
. In most cases, it’s easiest to just pass the pid-file via the--pidfile $PID
option (you might find some scripts online that pass--exec $DAEMON
as a second matching option, but this didn’t work for me).
Just copy this script into /etc/init.d/
, given it 755
permissions, and add it to the init sequence with sudo update-rc.d spawn-fcgi-php defaults
. After a quick reboot, you should see 6 php-cgi
processes running.
Jerad Jackson
10.23.2011
Thanks for the init script!