🎸 Django Advanced

What is Django's deployment best practices?

Answer

Production-ready Django deployment: WSGI/ASGI servers: never use Django's dev server in production. Use: Gunicorn (gunicorn myproject.wsgi:application -w 4 --timeout 120), uWSGI, Daphne (for async/WebSockets). Web server (reverse proxy): Nginx in front of Gunicorn: handles SSL termination, static/media files, load balancing, request buffering. Nginx config: location /static/ { alias /var/www/myapp/staticfiles/; expires 1y; add_header Cache-Control "public, immutable"; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }. Database: use PostgreSQL for production. Connection pooling: PgBouncer between Django and PostgreSQL. Set CONN_MAX_AGE in DATABASES for persistent connections: "CONN_MAX_AGE": 60. Static files: python manage.py collectstatic. Serve via Nginx or WhiteNoise. Use CDN for global distribution. Environment variables: use python-decouple or django-environ. Never commit secrets. Process management: Supervisor or systemd to keep Gunicorn running, auto-restart on crash, log management. Docker: Dockerfile with multi-stage build — builder installs dependencies, final image is minimal. CMD ["gunicorn", "myproject.wsgi:application", "--bind", "0.0.0.0:8000", "--workers", "4"]. Health checks: /health/ endpoint returns 200 — used by load balancers and Kubernetes. Logging: structured JSON logging to stdout/stderr (no file logging in containers). Migrations: run python manage.py migrate as part of deployment, before starting new server.