Django is a high-level Python web framework with a batteries-included philosophy. This guide deploys a Django application in production on Ubuntu 24.04 LTS using Gunicorn as the WSGI server and Nginx as the reverse proxy.

Tested and valid on:

  • Ubuntu 24.04 LTS

Prerequisites

  • Ubuntu 24.04 LTS server
  • Python 3.12 and pip installed
  • Nginx installed
  • A domain name pointed to your server

Step 1 – Create the Project and Virtual Environment

Set up the project:

mkdir /var/www/django_project && cd /var/www/django_project
python3.12 -m venv venv
source venv/bin/activate
pip install django gunicorn psycopg2-binary

Step 2 – Create a Django Project

Scaffold a new Django project:

django-admin startproject mysite /var/www/django_project

Step 3 – Configure Django for Production

Edit settings.py:

nano mysite/settings.py

Set:

DEBUG = False
ALLOWED_HOSTS = ['your_domain.com', 'www.your_domain.com']
STATIC_ROOT = '/var/www/django_project/staticfiles'

Step 4 – Collect Static Files

Gather all static files:

python manage.py collectstatic

Step 5 – Configure Gunicorn

Test Gunicorn manually:

gunicorn --bind 0.0.0.0:8000 mysite.wsgi

Create a systemd service:

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

Add:

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

[Service]
User=www-data
Group=www-data
WorkingDirectory=/var/www/django_project
ExecStart=/var/www/django_project/venv/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock mysite.wsgi:application

[Install]
WantedBy=multi-user.target

Enable and start:

sudo systemctl enable gunicorn
sudo systemctl start gunicorn

Step 6 – Configure Nginx

Create the Nginx server block:

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

Add:

server {
    listen 80;
    server_name your_domain.com;
    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ { root /var/www/django_project; }
    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

Enable and reload:

sudo ln -s /etc/nginx/sites-available/mysite /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

Step 7 – Add SSL

Secure with Let’s Encrypt:

sudo certbot --nginx -d your_domain.com

Conclusion

Your Django application is now deployed on Ubuntu 24.04 LTS with Gunicorn and Nginx. Gunicorn handles Python WSGI requests while Nginx serves static files and terminates SSL.