Deploy/Run a Django app with Nginx and Gunicorn in Ubuntu

The reason we need Nginx

If you followed the previous tutorial, we ran our django app with Gunicorn. However, at the end, we saw that the styles of the admin panel were gone. The reason is that Gunicorn is an application server and just runs the app (django app in our case) and django, as we know, does not serve static files except in development. Nginx to the rescue! It will be a reverse proxy for Gunicorn. What the hell is a reverse proxy? Good question! We all know what VPNs are, right? We use them to access some website that is blocked for some reason. In this case, we access that website through a VPN: We -> VPN -> some website. This kind of proxies are called Forward Proxies. As for reverse proxies, think of them as forced proxies. For example, a user is trying to access our django app running in gunicorn. He thinks that he is accessing the app directly. However, what is happening is that he is first accessing the Nginx server which decides what to do next. If the user is accessing a static file, the Nginx server will serve it itself. Otherwise, it will redirect it to Gunicorn. In plain terms, http requests will be handled by Gunicorn and static ones by Nginx. That’s why we need Nginx.

Apart from that, Nginx also improves performance, reliability, security and scale.


By now we already have Django and Gunicorn ready. So, let’s install Nginx now:

sudo apt-get install nginx

Now, we will configure Nginx to pass traffic to the process.

Create a file /etc/nginx/sites-available/domain and type in the following:

server {
    listen 8000;

    location = /favicon.ico { access_log off; log_not_found off; }

    location /static/ {
            root /home/ubuntu/myproject;

    location / {
            include proxy_params;

Now, let’s enable this file by linking it to the sites-enabled folder:

sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

Restart nginx:

sudo service nginx restart


FollowFollow on FacebookFollow on Google+Email this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *