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.
The deployment stack works by routing incoming HTTP requests from Nginx to Gunicorn, which then communicates with Django. Supervisor ensures Gunicorn restarts on failure.
# Install Gunicorn using pip
pip install gunicorn
# Run Django using Gunicorn with 3 workers
gunicorn --workers 3 myproject.wsgi:application
# Install Nginx on Ubuntu
sudo apt install nginx
# 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 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
Nginx receives the request → forwards it to Gunicorn → Gunicorn processes it via Django → response returns to the client.