Setup WSGI for Deployment
A snippet showing how to configure WSGI for deployment.
# Install a WSGI server
pip install gunicorn
# (Alternative)
pip install uwsgi
# project/wsgi.py
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.prod")
application = get_wsgi_application()
# Gunicorn (basic)
gunicorn project.wsgi:application
# Bind to network interface and set workers (general rule: 2-4 x CPU cores)
gunicorn --bind 0.0.0.0:8000 --workers 4 project.wsgi:application
# Daemonize to run in background (or prefer systemd below)
gunicorn --bind unix:/run/gunicorn.sock --workers 4 --daemon project.wsgi:application
# systemd service (Gunicorn) - /etc/systemd/system/gunicorn.service
[Unit]
Description=gunicorn daemon
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/srv/project
Environment="DJANGO_SETTINGS_MODULE=project.settings.prod"
ExecStart=/srv/venv/bin/gunicorn --workers 4 --bind unix:/run/gunicorn.sock project.wsgi:application
Restart=on-failure
[Install]
WantedBy=multi-user.target
# Enable & start
sudo systemctl daemon-reload
sudo systemctl enable gunicorn
sudo systemctl start gunicorn
# uWSGI alternative (ini file) - uwsgi.ini
[uwsgi]
chdir = /srv/project
module = project.wsgi:application
master = true
processes = 4
socket = /run/uwsgi.sock
chmod-socket = 660
vacuum = true
die-on-term = true
# Start
uwsgi --ini uwsgi.ini
# Result
- Django app runs behind a production-grade WSGI server (Gunicorn/uWSGI).
- Use a reverse proxy (e.g., Nginx) to serve static/media and proxy to the socket/port.
- Environment is isolated via venv; managed by systemd for reliability.
Explanation:
- WSGI is the standard for synchronous Django; choose ASGI for async/WebSockets.
- Prefer a Unix socket with Nginx for performance; fall back to TCP for simplicity.
-
Tune worker count based on CPU and workload; add
--timeoutfor long tasks. -
Keep
DJANGO_SETTINGS_MODULEpointing to your prod settings.