Hosting Django with Nginx

YouTube reference

Get 200$ in Digital Ocean and Get 100$ in Vultr

Nginx can serve as a great proxy for Django apps. Here’s how to configure it for a Django site.

Install Requirements

Install Nginx and Python on Ubuntu:

sudo apt update
sudo apt install nginx python3-pip python3-venv

Clone Sample App

We’ll use the django_web_sample app:

git clone https://github.com/ServerGuyFluxx/django_web_sample.git /var/www/django_web_sample

Set Up Virtual Environment

Create a Python virtual environment:

python3 -m venv /var/www/django_web_sample/myenv
source /var/www/django_web_sample/myenv/bin/activate
pip install -r /var/www/django_web_sample/requirements.txt

Configure Gunicorn

Create a gunicorn.service file:

nano /etc/systemd/system/gunicorn.service


[Unit]
Description=Gunicorn daemon
After=network.target

[Service]
User=root
Group=root
WorkingDirectory=/var/www/django_web_sample
ExecStart=/var/www/django_web_sample/myenv/bin/gunicorn --workers 3 --bind unix:/var/www/django_web_sample/django_web_sample.sock django_web_sample.wsgi:application

[Install]
WantedBy=multi-user.target

Configure Nginx

Update /etc/nginx/sites-available/default:

nano /etc/nginx/sites-available/default`

add following

server {
    listen 80;

    location / {
        include proxy_params;
        proxy_pass http://unix:/var/www/django_web_sample/django_web_sample.sock;
    }
}

finally restart and enable services

# Reload systemd daemon
sudo systemctl daemon-reload

# Enable gunicorn service 
sudo systemctl enable gunicorn  

# Start gunicorn
sudo systemctl start gunicorn

# Restart Nginx 
sudo service nginx restart

Now go to browser and type ip of the server and you should see website running .