Chuyển đến nội dung chính

Lesson 20: Production Deployment & Monitoring

Deploy Django + Nginx + Gunicorn. Sentry error tracking, structured logging. Prometheus metrics, Grafana dashboards. Django health checks, scaling strategies, zero-downtime deployment.

💻 Programming — Lesson 20 Lesson 20: Production Deployment & Monitoring

Django: From Basics to Advanced

Part 5: Testing, Deployment & Production

xdev.asia

1. Nginx + Gunicorn

upstream django {
    server web:8000;
}

server {
    listen 80;
    server_name example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com;

    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;

    client_max_body_size 10M;

    location /static/ {
        alias /app/staticfiles/;
        expires 30d;
    }

    location /media/ {
        alias /app/media/;
    }

    location / {
        proxy_pass http://django;
        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;
    }
}
# gunicorn.conf.py
import multiprocessing

bind = '0.0.0.0:8000'
workers = multiprocessing.cpu_count() * 2 + 1
worker_class = 'gthread'
threads = 2
timeout = 120
accesslog = '-'
errorlog = '-'
loglevel = 'info'

2. Sentry Error Tracking

pip install sentry-sdk
import sentry_sdk

sentry_sdk.init(
    dsn=os.environ['SENTRY_DSN'],
    traces_sample_rate=0.1,
    profiles_sample_rate=0.1,
    environment=os.environ.get('ENVIRONMENT', 'production'),
)

3. Structured Logging

# settings.py
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'json': {
            '()': 'pythonjsonlogger.jsonlogger.JsonFormatter',
            'format': '%(asctime)s %(name)s %(levelname)s %(message)s',
        },
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'json',
        },
    },
    'loggers': {
        'django': {'handlers': ['console'], 'level': 'WARNING'},
        'apps': {'handlers': ['console'], 'level': 'INFO'},
    },
}

4. Health Checks

pip install django-health-check
INSTALLED_APPS = [
    ...,
    'health_check',
    'health_check.db',
    'health_check.cache',
    'health_check.contrib.celery',
    'health_check.contrib.redis',
]

urlpatterns = [
    path('health/', include('health_check.urls')),
]

5. Prometheus & Grafana

pip install django-prometheus
INSTALLED_APPS = [..., 'django_prometheus']
MIDDLEWARE = [
    'django_prometheus.middleware.PrometheusBeforeMiddleware',
    ...
    'django_prometheus.middleware.PrometheusAfterMiddleware',
]

urlpatterns = [
    path('', include('django_prometheus.urls')),
]

6. Zero-Downtime Deployment

#!/bin/bash
# deploy.sh
set -e
git pull origin main
docker compose build web
docker compose up -d --no-deps web
docker compose exec web python manage.py migrate --noinput
docker compose exec web python manage.py collectstatic --noinput
# Restart workers gracefully
docker compose exec web kill -HUP 1
echo "Deploy completed!"

Congratulations on completing the series Django: From Basics to Advanced! 🎉