Web Servers & Stacks Intermediate 20 min

How to Deploy a Python Django Application with Gunicorn and Nginx

Run production Django backends with virtual environments, Gunicorn Unix sockets, and static file caching

IndSoft Cloud Engineering
Reviewed October 2026
Production Verified Commands

Guide Overview & Architecture Outcome

By following this guide, you will deploy a production Python Django web application on Ubuntu. Gunicorn will serve dynamic requests over a protected Unix socket while Nginx serves static media assets and handles SSL encryption.

Prerequisites & System Requirements

An Ubuntu 22.04 or 24.04 VPS with Python 3 and pip installed.

1

Create Virtual Environment and Install Django and Gunicorn

Isolate your Python project dependencies in a dedicated virtualenv.

bash · step-1-command.sh
sudo apt install python3-venv python3-dev libpq-dev nginx -y python3 -m venv /var/www/myproject/env source /var/www/myproject/env/bin/activate pip install django gunicorn psycopg2-binary
Expected System Output:
Installed.
2

Create Systemd Socket and Service Files for Gunicorn

Create /etc/systemd/system/gunicorn.socket and gunicorn.service to automate process lifecycle.

bash · step-2-command.sh
sudo nano /etc/systemd/system/gunicorn.service # ExecStart=/var/www/myproject/env/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application sudo systemctl start gunicorn.socket sudo systemctl enable gunicorn.socket
Expected System Output:
Created symlink /etc/systemd/system/sockets.target.wants/gunicorn.socket
3

Configure Nginx to Proxy to Gunicorn Socket

Route static files directly from disk and proxy dynamic requests to the Unix socket.

bash · step-3-command.sh
sudo nano /etc/nginx/sites-available/myproject # location /static/ { alias /var/www/myproject/static/; } # location / { proxy_pass http://unix:/run/gunicorn.sock; } sudo systemctl reload nginx
Expected System Output:
Reloaded.

Check That It Worked (Verification)

Run this quick verification check to confirm your installation is responding properly:

verify-service.sh
sudo systemctl status gunicorn
Expected Response:
Active: active (running) with 3 worker processes.

Troubleshooting Common Errors

Quick resolutions for frequent setup pitfalls and configuration issues.

Diagnostic Tips
502 Bad Gateway from Nginx to Gunicorn
Verify that the Gunicorn socket file has correct permissions: ls -l /run/gunicorn.sock. The socket must be accessible by www-data.
DisallowedHost error at /
Add your domain or server IP to ALLOWED_HOSTS in your Django settings.py file.
Static CSS and images return 404
Run python manage.py collectstatic and verify the path matches the Nginx location /static/ directive.