Chapter 8: Application and containers¶
8.1 Django production settings¶
| Setting | Value |
|---|---|
DEBUG |
False |
ALLOWED_HOSTS |
exact domain(s) |
CSRF_TRUSTED_ORIGINS |
https://<domain> |
SECRET_KEY |
long random, per environment |
SECURE_PROXY_SSL_HEADER |
("HTTP_X_FORWARDED_PROTO", "https") (nginx sets it) |
SESSION_COOKIE_SECURE, CSRF_COOKIE_SECURE |
True |
SECURE_HSTS_SECONDS |
start small (e.g. 3600), raise later |
DATABASES[...]["OPTIONS"] |
{"sslmode": "require"} for RDS |
| App server | gunicorn <project>.wsgi:application --bind 0.0.0.0:8000 --workers N inside the container |
Run python manage.py check --deploy and fix every warning.
8.2 Compose file per server: the pattern¶
Files: docker-compose.yml (laptop only), docker-compose.staging.yml, docker-compose.prod.yml. Server .env contains COMPOSE_FILE=docker-compose.<env>.yml.
networks:
egress: { driver: bridge } # app → internet/AWS/RDS
db-net: { driver: bridge, internal: true } # only if Postgres is self-hosted
cache-net:{ driver: bridge, internal: true }
x-logging: &logging
logging: { driver: json-file, options: { max-size: "20m", max-file: "10" } }
x-app: &app
<<: *logging
restart: always
env_file: .env
security_opt: ["no-new-privileges:true"]
cap_drop: ["ALL"]
networks: [egress, cache-net] # + db-net if self-hosted Postgres
services:
api:
<<: *app
command: gunicorn project.wsgi:application --bind 0.0.0.0:8000 --workers 3
ports: ["127.0.0.1:8000:8000"] # loopback only, nginx in front (R2)
redis:
<<: *logging
image: redis:7-alpine
command: ["redis-server", "--requirepass", "${REDIS_PASSWORD:?set REDIS_PASSWORD}",
"--rename-command", "CONFIG", "", "--rename-command", "MODULE", ""]
networks: [cache-net] # no ports: (R3)
Self-hosted Postgres (staging-style) additionally:
- No
ports:; networkdb-net(internal). - Bootstrap superuser
postgreswith its own password; app role created by an init script withNOSUPERUSER NOCREATEDB NOCREATEROLE. pg_hba.confmounted read-only (./docker/postgres/pg_hba.conf:/etc/postgresql/pg_hba.conf:ro,-c hba_file=…). Allow the app subnet withscram-sha-256, rejectpostgresover TCP, reject everything else.-c log_connections=on -c log_disconnections=on -c log_statement=ddl.cap_drop: ALL+cap_add: CHOWN, DAC_OVERRIDE, FOWNER, SETUID, SETGID.
Required variables fail loudly: ${DB_PASSWORD:?Set DB_PASSWORD}. A missing secret stops the deploy instead of falling back to a default.
8.3 Secrets on the server¶
.envis in.gitignoreand.dockerignore..env.exampleholds names only, no usable values.- Change
.env→docker compose up -d --force-recreate <services>(H17). - Better long term: read the DB secret from Secrets Manager at startup (boto3) using the instance role, so no password sits in
.env.