Gunicorn init script with VirtualEnv

July 20, 2011

Here's a Gunicorn startup script for a Django app that is deployed within a virtualenv on Debian.

You'll need to change some of the settings at the start of this script, to indicate the name of the project and then owner home directory that its source is inside. You'll also need to set a port number.

Here's the key fields to change:

OWNER="tjs"
NAME="patrons1"
PORT=8001
WORKERS=1

This script assumes: We're using virtualenvwrapper scripts VirtualEnvs are located in .virtualenvs in the home directory of the user who owns the source files * Gunicorn is installed within the VirtualEnv

#!/bin/sh
### BEGIN INIT INFO
# Provides:       patrons1
# Required-Start: $local_fs $syslog
# Required-Stop:  $local_fs $syslog
# Default-Start:  2 3 4 5
# Default-Stop:   0 1 6
# Short-Description: Gunicorn processes for patrons1
### END INIT INFO

OWNER="drumcoder"
NAME="patrons1"
PORT=8001
WORKERS=1

VIRTUALENV=$APP
CONFDIR="/home/$OWNER/web/$NAME"
USER=www-data
VIRTUALENVDIR="/home/$OWNER/.virtualenvs"
GUNICORN_RUN="$VIRTUALENVDIR/$VIRTUALENV/bin/gunicorn_django"
PID="/tmp/gunicorn_$NAME.pid"
VENV_ACTIVATION="$VIRTUALENVDIR/initialize"
RETVAL=0

# source function library
. /lib/lsb/init-functions

start()
{
    echo "Starting $NAME."
    export PYTHONPATH=$PYTHONPATH:$CONFDIR;
    cd $CONFDIR/$NAME;
    su -c "$VENV_ACTIVATION; $GUNICORN_RUN -b localhost:$PORT -n $NAME -w $WORKERS -p $PID -D settingslive.py" $USER && echo "OK" || echo "failed";
}

stop()
{
    echo "Stopping $NAME"
    kill -QUIT `cat $PID` && echo "OK" || echo "failed";
}

reload()
{
    echo "Reloading $NAME:"
    if [ -f $PID ]
    then kill -HUP `cat $PID` && echo "OK" || echo "failed";
    fi
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    restart)
        reload
        ;;
    reload)
        reload
        ;;
    force-reload)
        stop && start
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart}"
        RETVAL=1
esac
exit $RETVAL

References