Container Entrypoint Hardening and Gunicorn Worker Configuration

Docker Django Linux

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 found evaluates as non-zero on every iteration, trapping the container in an infinite startup loop.
  • Environment variable drift: If the loop checks $SQL_HOST while 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:

  • --clear deletes the entire contents of STATIC_ROOT before 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 (sync worker 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, leaving docker logs blind 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

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.