Wednesday, May 29, 2013

Django + Gunicorn + Nginx + Supervisor

Here is an example to run and control a web application in a production server:

1. Django: our web development platform -

I have a django project located at '/home/projects/my_project/'

2. Gunicorn: the Python WSGI HTTP server, I use it to run our web application -

I will create a bash shell to run the gunicorn server at port 8000 inside the my_env virtual environment, named, place it inside the root dir of my django project (/home/projects/my_project/

set -e
LOGDIR=$(dirname $LOGFILE)
# user/group to run as
cd /home/projects/my_project
source /home/.venv/my_env/bin/activate
test -d $LOGDIR || mkdir -p $LOGDIR
exec gunicorn_django -w $NUM_WORKERS --bind=$ADDRESS --user=$USER --group=$GROUP --log-level=debug --log-file=$LOGFILE 2>>$LOGFILE 

Note: remember to create log directory at /home/projects/logs/ for gunicorn and /home/projects/logs/my_project/ for nginx

3. Nginx: the reverse proxy, to cache our static contents and to dispatch requests -


upstream my-app {
    server localhost:8000 fail_timeout=0;

server {
    listen 80;
    server_name localhost;
    access_log /home/projects/logs/my_project/access.log;
    error_log /home/projects/logs/my_project/error.log;

    location /static/ {
        alias /home/projects/my_project/static/;

    location / {
        proxy_pass http://my-app;                                                                                              


4. Supervisor: the process control system, it's used to control and monitor our gunicorn process, including


directory = /home/projects/my_project/
user = root
command = /home/projects/my_project/
stdout_logfile = /home/projects/logs/supervisor.log
stderr_logfile = /home/projects/logs/supervisor_error.log

Supervisor will help us start gunicorn server automatically (as a daemon) every time we restart the machine.

After all configurations have been properly set up, restart the server:

$ sudo service nginx restart
$ sudo supervisorctl restart gunicorn