Deploying a django project on nginx with gunicorn

Back when I started  working with django, one of the things that I found was sort of difficult to do was deploying a project, as suggested by the documentation, using apache and mod_wsgi (and previously with mod_python), at least when it came to serve several projects and its media at the same server. Doing all those things with nginx and gunicorn is shockingly easy.

To add a new site on nginx I just touch a new file in the /etc/nginx/sites-enabled, with the contents:

server {
    listen 80;

    location / {

Now, supposing I want to have acces and error logs, and serve my site’s and the admin site’s media, I would add some lines to the server:

access_log /var/www/django/myproject/access.log;
error_log /var/www/django/myproject/error.log;

location /media {
    root /var/www/django/myproject;

location /admin_media {
    alias /usr/local/lib/python2.7/dist-packages/django/contrib/admin/media;

Where /media and /admin_media are the MEDIA_URL and ADMIN_MEDIA_PREFIX pointed by my That is, I have a media folder in my project root directory and the admin media is served directly from the django installation.

To actually run my django site on I create a gunicorn configuration file in my project root (where is located):

bind = ""
workers = 3

Assuming I named the file, gunicorn is run from the same directory doing:

gunicorn_django -c -D

And that’s it.

When the code is updated, there’s no need to restart nginx; instead, gunicorn is restarted (not so prettily) with:

kill -HUP <main gunicorn process id>

To serve multiple sites, just use differents ports (8888 in the example) in each one’s configuration file.

About these ads

Tags: , , ,

2 Responses to “Deploying a django project on nginx with gunicorn”

  1. rgviva Says:

    thanks for this post. This is indeed easy to config. I wonder though how this setup compares to apache+mod_wsgi performace wise. mod_wsgi loads into apache vs gunicorn which is a separate process. So – should i expect performance degradation?

    • facundoolano Says:

      Well, I went to nginx+gunicorn for simplicity, not performance, and I really don’t have basis for comparing the performances of both setups. I did read somewhere that nginx+gunicorn tends to be lighter in CPU and memory consumption, but maybe you should look up some benchmarks to get a good answer (and share it here :P)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.