How to Deploy Django using Gunicorn and Nginx in Ubuntu

How to Deploy Django using Gunicorn and Nginx in Ubuntu

How to Deploy Django using Gunicorn and Nginx in Ubuntu

 

Your Django web application can benefit from a safe and reliable web serving environment by being deployed using Ubuntu's Gunicorn and Nginx. Nginx is a high-performance, open-source web server that also serves as a reverse proxy, whereas Gunicorn is a Python WSGI HTTP server.

 

# 1

First login into your ubuntu machine and Do basic Setup

 

sudo apt update
sudo apt install python3-pip python3-dev nginx
sudo -H pip3 install --upgrade pip
sudo pip3 install virtualenv
sudo apt install python3-virtualenv
pip install gunicorn django

 

# 2

Create simple Django Project

 

django-admin startproject server

 

 # 3

go to server/settings.py

 

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static")
MEDIA_URL='/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

 

# 4

Enable 8000 port for testing purpose

 

sudo ufw allow 8000

 

# 5

Run development server

 

gunicorn --bind 0.0.0.0:8000 server.wsgi

 

# 6

Now going to do background service for django using gunicorn

 

sudo nano /etc/systemd/system/gunicorn.service

 

[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/server
ExecStart=/home/ubuntu/env/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8000 server.wsgi:application
[Install]
WantedBy=multi-user.target

 

# 7

Start your server

 

sudo systemctl daemon-reload
sudo systemctl start gunicorn
sudo systemctl enable gunicorn

 

#

Gunicorn Status checking

 

sudo systemctl status gunicorn

 

# 9

Now going to setup Nginx Server for Gunicorn Server

 

sudo nano /etc/nginx/sites-available/server

 

# 10

Nginx config 

 

server {
    listen 80;
    server_name <ip_address> <domain_name>;
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /var/www/server;
    }
    location /media/ {
        root /var/www/server;
    }
location / {
        include proxy_params;
        proxy_pass http://127.0.0.1:8000;
    }

 

# 11

Copy and Paste nginx server config

 

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

 

# 12

Test nginx config file

 

sudo nginx -t

 

# 13

Restart nginx server

 

sudo systemctl restart nginx

 

# 14

Disable 8000

 

sudo ufw delete allow 8000

 

 # 15

Full firewall permission to nginx

 

sudo ufw allow 'Nginx Full'

 

 # 16

Restart nginx server

 

sudo systemctl restart nginx

 

 

Happy Coding !!!

Share