How to set Gunicorn to use with Multiple sites for Django?

February 5, 2016 2k views
Django Debian

I spent two days working with Gunicorn and I couldn't get it working. I followed many tutorials on DigitalOcean and other external resources and now I finally am posting my question with all the settings I worked with for last couple of days.

I am using Gunicorn 18.0.0 along with Supervisor and Nginx. My project structure is /home/umer/myvirtualenv/myproject.

I got my gunicorn upstart script in /home/umer/myvirtualenv/bin/gunicorn_start including following information:

NAME="zik"                                    # Name of the application
DJANGODIR=/home/umer/myvirtualenv/myproject# Django project directory
SOCKFILE=/home/umer/myvirtualenv/myproject/run/gunicorn.sock  # we will communicte using this unix socket
USER=umer                                        # the user to run as
GROUP=webapps                                     # the group to run as
NUM_WORKERS=3                                     # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=myproject.settings             # which settings file should Django use
DJANGO_WSGI_MODULE=myproject.wsgi                     # WSGI module name

echo "Starting $NAME as `whoami`"

# Activate the virtual environment
cd $DJANGODIR
source ../bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH

# Create the run directory if it doesn't exist
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR

# Start your Django Unicorn
# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
  --name $NAME \
  --workers $NUM_WORKERS \
  --user=$USER --group=$GROUP \
  --bind=unix:$SOCKFILE \
  --log-level=debug \
  --log-file=-

For Nginx I have my settings like following:

upstream myproject_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).

  server 127.0.0.1:9000 fail_timeout=0;
}

server {

    listen   80;
    server_name example.com;

    client_max_body_size 4G;

    access_log /home/umer/myvirtualenv/myproject/logs/nginx-access.log;
    error_log /home/umer/myvirtualenv/myproject/logs/nginx-error.log;

    location /static/ {
        alias   /umer/myvirtualenv/myproject/static;
    }

    location /media/ {
        alias   /umer/myvirtualenv/myproject/media/;
    }

    location / {
        # an HTTP header important enough to have its own Wikipedia entry:
        #   http://en.wikipedia.org/wiki/X-Forwarded-For
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # enable this if and only if you use HTTPS, this helps Rack
        # set the proper protocol for doing redirects:
        # proxy_set_header X-Forwarded-Proto https;

        # pass the Host: header from the client right along so redirects
        # can be set properly within the Rack application
        proxy_set_header Host $http_host;

        # we don't want nginx trying to do something clever with
        # redirects, we set the Host: header above already.
        proxy_redirect off;

        # set "proxy_buffering off" *only* for Rainbows! when doing
        # Comet/long-poll stuff.  It's also safe to set if you're
        # using only serving fast clients with Unicorn + nginx.
        # Otherwise you _want_ nginx to buffer responses to slow
        # clients, really.
        # proxy_buffering off;

        # Try to serve static files from nginx, no point in making an
        # *application* server like Unicorn/Rainbows! serve static files.
        if (!-f $request_filename) {
            proxy_pass http://myproject_server;
            break;
        }
    }

    # Error pages
    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /umer/myvirtualenv/myproject/static;
    }
}

My Gunicorn config file in /etc/gunicorn.d/gunicorn.py includes following:

"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
from os import environ


def max_workers():
    return cpu_count() * 2 + 1

max_requests = 1000
worker_class = 'gevent'
workers = max_workers()

I've associated my sites-available in sites-enabled. My gunicorn socket is under the directory /home/umer/myvirtualenv/myproject/run/gunicorn.sock

My supervisor configurations in /etc/supervisor/conf.d/myproject.conf are following:

[program:gunicorn]                              
command = /home/umer/myvirtualenv/bin/gunicorn myproject.wsgi:application --bind example.com:8000 --workers=3 --pid /tmp/gunicorn.pid
                                                                                                ; Command to start
user = umer                                                                                     ; User to run as
stdout_logfile = /home/umer/myvirtualenv/logs/gunicorn_supervisor.log                           ; Where to write log messages
redirect_stderr = true                                                                          ; Save stderr in the same log   
environment=LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8                                                 ; Set UTF-8 as default encoding

Kindly advise so I can get this done.

1 Answer

How did you solve your problem?

Have another answer? Share your knowledge.