Deploy your Django App with Nginx and Gunicorn
Samschtig,09 Oktoober, 2021

There are several ways to deploy your Django project. In this day and age there are several new services that let you deploy an app just with a config file without having to deal with web servers or WSGI.

But if you want to run your own server (e.g. via the excellent Hetzner Cloud that starts at few Euro per month) that might come up cheaper then all these services) one of the easiest way to get your project running is with with Nginx and Gunicorn.

Here is how to do it in simple steps:

Step 1 Configure Nginx

create a file with the name of your domain/website in the directory /etc/nginx/sites-enabled

server { 
server_name    YOURDOMAIN.COM;

location /static/ {
    root  /home/USER/YOURPROJECTDIRECTORY;
}


location / {
  proxy_pass      http://127.0.0.1:8081;
}

}

We have three actions in the configuration file. First you need to type your server name e.g. YOURDOMAIN.COM
secondly, have configure all the /static/ file to be from the django project directory. You should not type yourproject/static but just the main project directory.
Lastly, we configure a proxy for port 8081 (of course you can change this port).

This setup will listen to port 8081.
To run your Django script with gunicorn you just use:

gunicorn YOURDJANGOPROJECT.wsgi --workers 5  --bind 127.0.0.1:8081

(obviously you can configure the numer of workes or even add threads) and you are live !

Bonus: to add the SSL certificate run

sudo certbot --nginx

after you create the config file as above in /etc/nginx/sites-enabled