← Back to Chapters

Deploying Django with Gunicorn, Nginx & Supervisor

? Deploying Django with Gunicorn, Nginx & Supervisor

? Quick Overview

When deploying a Django application in production, efficiency, security, and reliability are essential. This setup uses Gunicorn as the WSGI server, Nginx as a reverse proxy, and Supervisor to manage processes and ensure high availability.

? Key Concepts

  • Gunicorn: Handles Django requests using WSGI.
  • Nginx: Manages HTTP requests and serves static files.
  • Supervisor: Keeps Gunicorn running automatically.

? Syntax & Theory

The deployment stack works by routing incoming HTTP requests from Nginx to Gunicorn, which then communicates with Django. Supervisor ensures Gunicorn restarts on failure.

⚙️ Installing & Running Gunicorn

? View Code Example
# Install Gunicorn using pip
pip install gunicorn
? View Code Example
# Run Django using Gunicorn with 3 workers
gunicorn --workers 3 myproject.wsgi:application

? Configuring Nginx

? View Code Example
# Install Nginx on Ubuntu
sudo apt install nginx
? View Code Example
# Nginx configuration for Django with Gunicorn
server {
    listen 80;
    server_name mydomain.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location /static/ {
        alias /path/to/static/;
    }

    location /media/ {
        alias /path/to/media/;
    }
}

? Supervisor Configuration

? View Code Example
# Supervisor config to manage Gunicorn
[program:myproject]
command=/path/to/venv/bin/gunicorn --workers 3 myproject.wsgi:application
directory=/path/to/myproject/
autostart=true
autorestart=true
stderr_logfile=/var/log/myproject.err.log
stdout_logfile=/var/log/myproject.out.log

? Live Output / Explanation

What Happens?

Nginx receives the request → forwards it to Gunicorn → Gunicorn processes it via Django → response returns to the client.

? Interactive Deployment Flow

? Client
? Nginx
? Gunicorn
?️ Django
Click button to start request flow...

? Use Cases

  • Production-ready Django deployments
  • Scalable web applications
  • High-availability backend services

? Tips & Best Practices

  • Match Gunicorn workers to CPU cores
  • Always serve static files via Nginx
  • Use Supervisor logs for debugging

? Try It Yourself

  • Deploy a sample Django app using this stack
  • Force-stop Gunicorn and watch Supervisor restart it
  • Add HTTPS using Let’s Encrypt