Container Entrypoint Hardening and Gunicorn Worker Configuration
A container's entrypoint.sh governs how the application transitions from image startup to serving live traffic. Common defaults—running POSIX shell scripts without error propagation (set -e), polling databases with ad-hoc nc loops, re-collecting static files on boot, and launching Gunicorn with bare flags—introduce silent failure modes and single-request bottlenecks in production.
Un-hardened Entrypoint Hardened Entrypoint
┌──────────────────────────────────────┐ ┌──────────────────────────────────────┐
│ #!/bin/sh (no set -e) │ │ #!/bin/sh │
│ while ! nc -z $SQL_HOST... (broken) │ │ set -e (fail fast on migrate error) │
│ python manage.py migrate (ignored!) │ ───► │ python manage.py migrate --noinput │
│ collectstatic --clear (runtime 404s) │ │ (Compose handles DB service_healthy) │
│ gunicorn (1 sync worker, no logs) │ │ gunicorn --workers 3 --timeout 60 \ │
└──────────────────────────────────────┘ │ --access-logfile - │
└──────────────────────────────────────┘
1. Fail-Fast Execution with set -e
By default, POSIX /bin/sh and bash continue executing subsequent lines after a command fails. If python3 manage.py migrate exits with a non-zero code (for example, due to a conflicting migration, locked table, or unreachable database), a script without set -e ignores the failure and launches Gunicorn anyway—serving traffic against an unmigrated schema.
Placing set -e at the top of entrypoint.sh aborts the script immediately when any untested command returns a non-zero exit code, allowing the container runtime (Docker Compose restart policy or orchestrator) to detect the crash and surface the error in logs.
2. Orchestrator Healthchecks vs. Shell Wait Loops
Legacy Docker entrypoints frequently include a while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1; done loop to wait for PostgreSQL. This pattern carries two operational risks:
- Missing binary in minimal images: Slim and distroless images do not include
netcat(nc). If the loop branch is triggered,nc: not foundevaluates as non-zero on every iteration, trapping the container in an infinite startup loop. - Environment variable drift: If the loop checks
$SQL_HOSTwhile the application reads$POSTGRES_HOST, the check is either skipped or polls an empty hostname.
Instead of polling inside the application container, delegate startup ordering to the orchestrator using a native database healthcheck:
services:
web:
depends_on:
db:
condition: service_healthy
3. Avoid Runtime collectstatic --clear When Assets Are Built into the Image
When static files are compiled and collected during the image build (Dockerfile.prod via Multi-Stage Docker Builds for Frontend Assets and Static Collection), running python manage.py collectstatic --noinput --clear inside entrypoint.sh is counterproductive:
--cleardeletes the entire contents ofSTATIC_ROOTbefore copying and re-hashing files from scratch on every container start or restart.- It adds several seconds of startup latency and creates a race window during rolling restarts where requests for CSS or JS assets return
404 Not Found.
4. Gunicorn Worker Concurrency, Timeouts, and Access Logging
When invoked without flags (gunicorn core.wsgi:application --bind 0.0.0.0:8000), Gunicorn defaults to:
--workers 1(syncworker class): Only one HTTP request can be processed at a time. A single slow operation—such as a synchronous outbound SMTP call (see Unprotected Public Form Risks - Synchronous SMTP DoS and Quota Exhaustion) or a slow database query—blocks every other visitor until it completes.--timeout 30: Workers blocked for 30 seconds are forcefully killed (SIGABRT) and restarted.- No access logs (
--access-logfile None): Standard HTTP request logs are suppressed, leavingdocker logsblind to request volume, status codes, and latency spikes.
Hardening the production invocation to:
gunicorn core.wsgi:application --bind 0.0.0.0:8000 --workers 3 --timeout 60 --access-logfile -
provides multi-worker concurrency on a single-core or dual-core VPS (2 * CPU + 1), tolerates longer upstream network waits without premature worker kills, and streams HTTP access logs directly to stdout (-).
References
- GNU Bash Manual: The Set Builtin (
set -e) - Howset -ecauses the shell to exit immediately when a command returns a non-zero status. - Gunicorn Documentation: Settings (
workers,timeout,accesslog) - Default values and sizing guidance ((2 x $num_cores) + 1) for Gunicorn workers and stdout logging. - Docker Compose Specification:
depends_on(service_healthy) - Waiting for a dependency container's healthcheck to pass before starting dependent services. - Docker and Django Build and Runtime Hardening – Entrypoint, Multi-Stage Assets, and Compose Volumes - Lab where
entrypoint.shand Gunicorn settings were hardened. - Unprotected Public Form Risks - Synchronous SMTP DoS and Quota Exhaustion - How a single synchronous Gunicorn worker amplifies blocking I/O into a full-site DoS.
- Docker and Container Security MOC & Web Application and Django Security MOC - Domain hubs.
Review cards
Flashcard What happens when `migrate` fails in an entrypoint without `set -e`?
The script carries on and starts Gunicorn, which serves traffic against an unmigrated schema. With set -e the container exits and the error shows up in the logs.
Flashcard Why can a `while ! nc -z …` wait loop hang a container forever?
Slim and distroless images don't ship nc, so every check fails with nc: not found and the loop never ends. Let Compose wait instead, with depends_on: condition: service_healthy.
Flashcard Why drop `collectstatic --clear` from the entrypoint when static files are built into the image?
It wipes STATIC_ROOT and rebuilds it on every start: seconds of extra startup, and CSS/JS 404s during rolling restarts.
Flashcard Why can one slow SMTP call take down a site running Gunicorn with default flags?
The default is a single sync worker, which handles one request at a time, so every other visitor waits until the call returns.