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 - https://www.djangoproject.com/

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 - http://gunicorn.org/

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



#!/bin/bash
set -e
LOGFILE=/home/projects/logs/gunicorn.log
LOGDIR=$(dirname $LOGFILE)
NUM_WORKERS=3
# user/group to run as
USER=root
GROUP=root
ADDRESS=0.0.0.0:8000
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 - http://nginx.org/

/etc/nginx/sites-available/default


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

/etc/supervisor/conf.d/gunicorn.conf

[program:gunicorn]
directory = /home/projects/my_project/
user = root
command = /home/projects/my_project/gunicorn.sh
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

Comments