Production Checklist¶
What to check before you open access to real users.
Why you need a checklist¶
Dev and production are different environments. Django has convenient defaults for dev (DEBUG=True, SQLite, InMemory channels), but they are completely unsafe for production. A checklist helps you not miss a single critical change.
Dev: DEBUG=True → stack trace with SECRET_KEY is visible → attacker forges cookies
Prod: DEBUG=False → empty 500 error, SECRET_KEY hidden
Dev: SQLite → file is destroyed on docker compose down
Prod: PostgreSQL → named volume, data persists between restarts
Dev: InMemory → WebSocket only within one process
Prod: Redis → broadcast between several workers
Dev: runserver → WSGI, single-threaded, no static files
Prod: Uvicorn + nginx → ASGI, several workers, static without Python
Security (mandatory)¶
- [ ]
SECRET_KEY— unique, 50+ characters, generated withget_random_secret_key() - [ ]
DEBUG = False— NEVER True in production - [ ]
ALLOWED_HOSTS— specific domains, not['*'] - [ ]
CSRF_TRUSTED_ORIGINS— contains the prod domain and the ngrok domain - [ ]
SESSION_COOKIE_SECURE = True— cookie over HTTPS only - [ ]
CSRF_COOKIE_SECURE = True - [ ]
SECURE_SSL_REDIRECT = True— HTTP → HTTPS redirect - [ ]
SECURE_HSTS_SECONDS = 31536000— HSTS for 1 year - [ ]
.envis in.gitignore— checkgit statusbefore pushing - [ ] Passwords are in
.env, not in the code or the Dockerfile
HTTPS settings in settings.py¶
# settings.py — uncomment when you have an SSL certificate:
SESSION_COOKIE_SECURE = True # cookie over HTTPS only
CSRF_COOKIE_SECURE = True
SECURE_SSL_REDIRECT = True # HTTP → HTTPS redirect
SECURE_HSTS_SECONDS = 31536000 # the browser remembers HTTPS for 1 year
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
Performance¶
- [ ] Remove
--reloadfromentrypoint.sh(uvicorn) - [ ] Add
--workers 4to uvicorn (4 = 2 × CPU cores) - [ ]
CONN_MAX_AGE = 0for ASGI (async-compatible) - [ ] nginx
expires 7dfor static files (caching) - [ ] PostgreSQL
max_connectionsmatches the number of uvicorn workers - [ ] Redis
maxmemory-policy allkeys-lru(don't let Redis fill up RAM)
Production entrypoint.sh¶
# entrypoint.sh in production — remove --reload, add --workers:
exec python -m uvicorn notes_project.asgi:application \
--host 0.0.0.0 \
--port 8001 \
--workers 4
Django deployment check¶
It shows warnings about security settings. In production they should all be green.
# With DEBUG=True (expected in dev):
WARNINGS:
?: (security.W004) You have not set a value for the SECURE_HSTS_SECONDS setting.
?: (security.W008) Your SECRET_KEY has less than 50 characters.
?: (security.W012) SESSION_COOKIE_SECURE is not set to True.
?: (security.W016) You have 'django.middleware.csrf.CsrfViewMiddleware' in your
MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True.
# With DEBUG=False and correct settings:
System check identified no issues (0 silenced).
Generating a SECRET_KEY¶
# Option 1: Python (via Docker)
docker compose run --rm web python -c \
"from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
# Option 2: Python (locally)
python3 -c "from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())"
# Option 3: OpenSSL
openssl rand -base64 50
# Option 4: Python secrets
python3 -c "import secrets; print(secrets.token_urlsafe(50))"
NEVER use
Both of these values are public and do not protect cookies or HMAC signatures.Pre-deploy checks¶
1. Check the tests¶
docker compose run --rm web python manage.py test notes_app.tests --failfast
# All tests must be green before deploying
2. Check migrations¶
docker compose exec web python manage.py showmigrations
# All migrations should have [X]
# If there is [ ] → migrate did not run or there is a new unapplied migration
docker compose exec web python manage.py migrate --check
# Returns exit code 1 if there are unapplied migrations
3. Check static files¶
docker compose exec nginx curl -I http://localhost/static/admin/css/base.css
# HTTP/1.1 200 OK → nginx serves static files correctly
# HTTP/1.1 404 → collectstatic did not run or the volume is not mounted
docker compose exec web python manage.py collectstatic --dry-run --noinput
# Shows what would be collected without actually copying
4. Check the list of environment variables¶
docker compose exec web env | sort | grep -vE 'PATH|HOME|USER|SHELL'
# Make sure these exist: SECRET_KEY, DATABASE_URL, REDIS_URL, ALLOWED_HOSTS
# Make sure DEBUG=False
# Make sure SECRET_KEY != 'dev-secret-key-...'
Monitoring and logging¶
- [ ]
LOGGINGinsettings.py→ files or stdout for Docker - [ ] nginx access log → analysis (Grafana Loki or ELK)
- [ ] Health check endpoints respond
- [ ] Uptime monitor (UptimeRobot, Better Stack)
# settings.py — basic logging configuration:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {message}',
'style': '{',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'verbose', # stdout → docker logs → centralized logging
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
'loggers': {
'django.request': {
'handlers': ['console'],
'level': 'WARNING', # only 4xx and 5xx, not every GET
'propagate': False,
},
},
}
# View logs per service:
docker compose logs --since 1h web # logs for the last hour
docker compose logs --since 1h nginx # nginx access log
docker compose logs --since 1h --follow web # live streaming
Backing up PostgreSQL¶
Before any deploy that changes the schema — make a backup:
# Back up the DB to a file:
docker compose exec db pg_dump \
-U notes_user \
-d notes_db \
-F c \
-f /tmp/backup_$(date +%Y%m%d_%H%M%S).dump
# Copy the backup from the container to the host:
docker cp $(docker compose ps -q db):/tmp/backup_*.dump ./backups/
# Restore from the backup:
docker compose exec db pg_restore \
-U notes_user \
-d notes_db \
-F c \
/tmp/backup.dump
Rollback¶
If a deploy broke the application — the rollback plan:
1. Roll back the code (previous Docker image)¶
# Stop the current version:
docker compose down
# Build the previous image (if there is a tag):
git checkout v1.2.3
docker compose up --build
# Or use the cached image:
docker compose up # no --build, uses the previous build
2. Roll back migrations¶
# View the list of migrations:
docker compose exec web python manage.py showmigrations notes_app
# Roll back to a specific migration:
docker compose exec web python manage.py migrate notes_app 0005
# ↑ rolls back 0006, 0007, ... to the state after 0005
# WARNING: deletes data from new columns!
Migrations with data
Rolling back a migration that removed a column → impossible (the data is already deleted). Rolling back a migration that added a column → safe (the empty column is simply removed). Always make a backup before a deploy with migrations.
Common mistakes on the first deploy¶
| Error | Cause | Fix |
|---|---|---|
403 CSRF verification failed |
Domain not in CSRF_TRUSTED_ORIGINS |
Add the domain in settings.py + env |
DisallowedHost |
Domain not in ALLOWED_HOSTS |
Add the domain + restart |
WebSocket 403 |
Auth is not passed through nginx | Check proxy_set_header in nginx.conf |
Static files 404 |
collectstatic did not run |
Check entrypoint.sh + volume mount |
ERR_NGROK_8012 |
ngrok cannot find nginx | Check that both are in app-net |
TimeoutError reading from redis |
socket_timeout in RedisChannelLayer |
socket_timeout=None in CONFIG |
CommandError: Demo data disabled |
seed_demo_data is disabled without DEBUG=True |
Add --force to the command |
SynchronousOnlyOperation in a consumer |
sync ORM in an async context | @database_sync_to_async |
Data disappeared after docker compose down |
down -v was used |
Back up before down -v |
web unhealthy → nginx does not start |
Migrate fails or uvicorn does not start | docker compose logs web |
| WS connection does not open through nginx | Missing WebSocket headers | Add proxy_http_version 1.1 in nginx.conf |
SECRET_KEY changed → all sessions invalid |
Changing SECRET_KEY → Django invalidates sessions | Don't change SECRET_KEY unless necessary |
In the book¶
- Part XI. Deployment — production deploy pipeline, environment management, scaling
- Part VII. Auth and Security — OWASP Top 10, XSS, CSRF, SQL Injection, Django security settings
Official documentation¶
- Django: Deployment checklist —
manage.py check --deploy, all security settings - Django: Security in Django — overview of all mechanisms
- Django: Logging —
LOGGINGconfiguration - Uvicorn: Settings —
--workers,--host,--portflags - nginx: Reverse proxy — proxy_pass, upstream
- PostgreSQL: pg_dump — backup and restore