Skip to content

Instantly share code, notes, and snippets.

@prestontimmons
Last active December 13, 2016 15:46
Show Gist options
  • Save prestontimmons/5509544 to your computer and use it in GitHub Desktop.
Save prestontimmons/5509544 to your computer and use it in GitHub Desktop.
Gunicorn init script

Includes a reload and update command.

Reload sends a SIGHUP to the gunicorn process. This does a graceful reload if the preload option isn't set.

Update sends a SIGUSR2 which starts a new master process. It then sends a QUIT to the old process, which gracefully shuts it down after all connections are closed. This works with the preload option.

I got the idea from Benoit's comment, here:

benoitc/gunicorn#402 (comment)

#!/bin/sh
# chkconfig: 345 85 15
# description: Starts gunicorn process
ENV="/home/sites"
SITE="mysite"
PORT=8050
USER="user"
PID="/var/run/gunicorn-${SITE}.pid"
WORKERS=4
COMMAND="$ENV/bin/gunicorn $SITE.wsgi:application -b 127.0.0.1:$PORT --user=$USER --pid=$PID --daemon -w $WORKERS -n gunicorn_$SITE --preload"
start()
{
echo "Starting $SITE"
su -c "$COMMAND" && echo "OK" || echo "failed";
}
stop()
{
if [ -f $PID ]
then
kill -QUIT `cat $PID` && echo "OK" || echo "failed";
echo "Stopping $SITE"
else
echo "Site $SITE is not running"
fi
}
reload()
{
if [ -f $PID ]
then
echo "Reloading $SITE:"
kill -HUP `cat $PID` && echo "OK" || echo "failed";
else
echo "Site $SITE is not running"
fi
}
update()
{
echo "Switch process for $SITE (`cat $PID`)"
local OLDPID="${PID}.oldbin"
if [ ! -f ${OLDPID} ]
then
kill -s USR2 `cat "$PID"`
fi
sleep 1
if [ ! -f ${OLDPID} ]
then
echo "New master process not started. Aborting."
return 1
fi
if [ ! -f ${PID} ]
then
echo "No process running. Aborting."
return 1
fi
kill -s QUIT `cat "$OLDPID"`
echo "New process running for $SITE (`cat $PID`)"
return 0
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
stop && start
;;
reload)
reload
;;
update)
update
;;
*)
echo $"Usage: $0 {start|stop|restart|reload}"
RETVAL=1
esac
exit $RETVAL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment