Host Django Application using Gunicorn & NGINX

Dhiraj Beri

Python Developer

Based in Gujarat, India

Step 1 - Installing python and nginx

Let's update the server's package index using the command below:

sudo apt update
sudo apt install python3-pip python3-dev nginx
This will install python, pip and nginx server

Step 2 - Creating a python virtual environment

sudo pip3 install virtualenv
This will install a virtual environment package in python. Let's create a project directory to host our Django application and create a virtual environment inside that directory.

git clone {project}
cd ~/{project}
virtualenv env
A virtual environment named env will be created. Let's activate this virtual environment:

source env/bin/activate

Step 3 - Installing Django and gunicorn

pip install django gunicorn
This installs Django and gunicorn in our virtual environment

Step 4 - Setting up our Django project

Add your IP address or domain to the ALLOWED_HOSTS variable in

If you have any migrations to run, perform that action:

~/{project}/ makemigrations
~/{project}/ migrate

Step 5 - Configuring gunicorn

Deactivate the virtualenvironment by executing the command below:

Let's create a system socket file for gunicorn now:

sudo vim /etc/systemd/system/gunicorn.socket
Paste the contents below and save the file

Description=gunicorn socket


Next, we will create a service file for gunicorn

sudo vim /etc/systemd/system/gunicorn.service
Paste the contents below inside this file:

Description=gunicorn daemon

ExecStart=/home/{user}/{project}/env/bin/gunicorn \
          --access-logfile - \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \

Lets now start and enable the gunicorn socket

sudo systemctl start gunicorn.socket
sudo systemctl enable gunicorn.socket

Step 6 - Configuring Nginx as a reverse proxy

Create a configuration file for Nginx using the following command

sudo vim /etc/nginx/sites-available/{project_name}
Paste the below contents inside the file created

server {
    listen 80;
    server_name {your_domain};

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/{user}/{project};

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
Activate the configuration using the following command:

sudo ln -s /etc/nginx/sites-available/{project_name} /etc/nginx/sites-enabled/
Restart nginx and allow the changes to take place.

sudo systemctl restart nginx
Your Django website should now work fine! Happy Coding :)


Medium Python Django Deployment