Docker and Django Build and Runtime Hardening – Entrypoint, Multi-Stage Assets, and Compose Volumes

Docker Django Linux

Goal

Audit and harden the Docker, Tailwind CSS, Gunicorn, and Django configuration across development and production (entrypoint.sh, Dockerfile, Dockerfile.prod, .dockerignore, tailwind.config.js, settings.py, docker-compose.yml, and docker-compose-prod.yml) to eliminate silent startup failures, runtime asset race conditions, permission mismatches, build-context pollution, and ephemeral data loss.

Setup

Prior to this review, the containerized Django stack exhibited five structural weaknesses across its build and runtime pipelines:

  1. entrypoint.sh ran without set -e, contained a broken nc -z database wait loop referencing undefined environment variables (DATABASE, SQL_HOST, SQL_PORT) without netcat installed in the image, re-ran collectstatic --clear on every production container restart, and launched Gunicorn with its default single synchronous worker (1 worker, 30s timeout, no stdout access logs).
  2. Dockerfile.prod ran collectstatic without compiling Tailwind CSS, relying on whatever static/css/output.css existed on the host, while tailwind.config.js omitted ./static/js/main.js from its content scan.
  3. Dockerfile referenced $APP_HOME before defining it (causing RUN mkdir $APP_HOME/staticfiles to create /staticfiles at the filesystem root as root after chown), while Dockerfile.prod and settings.py nested STATIC_ROOT under /app/django-app/staticfiles while MEDIA_ROOT lived at /app/mediafiles.
  4. .dockerignore did not exclude .venv/, node_modules/, staticfiles/, or mediafiles/, allowing host macOS virtualenvs and Node binaries to leak into COPY . /app.
  5. Development and production Compose files had port, volume, and mount gaps: CSRF_TRUSTED_ORIGINS in docker-compose.yml was set to http://localhost:8000 despite the container publishing 8080:8000; the ./django-app:/app bind mount shadowed the image's /app/node_modules; and docker-compose-prod.yml lacked a persistent volume for /app/mediafiles.

Key ideas

  • Fail-fast container entrypoints (set -e): Without set -e, a failed python3 manage.py migrate does not stop the shell script; the container proceeds to start Gunicorn against an unmigrated or unreachable database.
  • Orchestrator healthchecks over shell polling: Hand-rolled while ! nc -z loops break silently when variable names drift or when netcat is stripped from minimal images. Docker Compose's depends_on with condition: service_healthy delegates readiness checks to the database container's native healthcheck.
  • Build-time vs. runtime static asset collection: When collectstatic is already executed during docker build, running collectstatic --noinput --clear inside entrypoint.sh on every restart deletes and re-hashes the static directory at runtime—adding startup latency and causing transient 404 responses during rolling restarts.
  • Gunicorn worker concurrency and observability: Gunicorn defaults to --workers 1, --timeout 30, and disabled stdout access logging. Raising concurrency to --workers 3 --timeout 60 --access-logfile - prevents a single slow synchronous request (such as an outbound SMTP call) from blocking all concurrent visitors and streams HTTP access logs to docker logs.
  • Self-contained multi-stage asset builds: Installing Node.js, running npm ci, and compiling minified Tailwind CSS (npx tailwindcss ... --minify) in the builder-base stage before collectstatic—then deleting node_modules prior to copying /app into the runtime stage—guarantees fresh CSS in production without shipping Node.js in the final image.
  • Tailwind content scanning for dynamic DOM scripts: Any JavaScript file that toggles utility classes at runtime (./static/js/main.js) must be listed in tailwind.config.js content so those classes are not purged during production minification.
  • Non-root directory creation and chown ordering: In a Dockerfile, ENV APP_HOME=/app must be declared before RUN mkdir -p, and all directory creation must happen before chown -R appuser:appuser /app and USER appuser to avoid root-owned directories and runtime PermissionError exceptions.
  • Build context isolation and anonymous volume masking: Excluding .venv/ and node_modules/ in .dockerignore prevents host-OS binary collisions during docker build, while an anonymous volume (- /app/node_modules) in development docker-compose.yml prevents a host bind mount (./django-app:/app) from overwriting the container's Linux node_modules.
  • Origin port alignment and persistent media storage: CSRF_TRUSTED_ORIGINS must match the host-mapped port (http://localhost:8080 for 8080:8000) that the browser sends in the Origin header, and production MEDIA_ROOT (/app/mediafiles) requires a named volume (media_data:/app/mediafiles) so user uploads survive container recreation.

In my own words

1. Entrypoint Hardening & Gunicorn Concurrency (entrypoint.sh)

A container entrypoint script is the boundary between infrastructure initialization and application serving. In the original script, omitting set -e meant that if python3 manage.py migrate exited with a non-zero status, the shell continued execution and booted Gunicorn over a broken schema. Adding set -e forces the container to terminate immediately on any unhandled command failure so Docker can surface the crash.

We also removed two obsolete startup steps:

  • The nc -z $SQL_HOST $SQL_PORT wait loop: Neither DATABASE, SQL_HOST, nor SQL_PORT existed in .env (which uses POSTGRES_HOST and POSTGRES_PORT), and netcat was not installed in the image. Setting DATABASE=postgres would have trapped the container in an infinite nc: not found loop. Container startup ordering is already enforced by Docker Compose's depends_on: db: condition: service_healthy.
  • Runtime collectstatic --noinput --clear: Because static assets are baked into the image during the Dockerfile.prod build stage, wiping and re-collecting them on every container boot slowed down startup and introduced a race window where requests could hit missing static files.

Finally, we replaced the bare gunicorn invocation with:

gunicorn core.wsgi:application --bind 0.0.0.0:8000 --workers 3 --timeout 60 --access-logfile -

Running 3 workers with a 60-second timeout prevents a single blocking I/O operation (such as synchronous SMTP in Unprotected Public Form Risks - Synchronous SMTP DoS and Quota Exhaustion) from starving the entire site, and --access-logfile - directs access logs to standard output for container log collection.

2. Multi-Stage Tailwind CSS Compilation (Dockerfile.prod & tailwind.config.js)

Previously, Dockerfile.prod executed python manage.py collectstatic --noinput without ever compiling Tailwind CSS. If static/css/output.css was missing or stale in the build context, the production image shipped with broken or unstyled pages. Furthermore, tailwind.config.js only scanned HTML templates, ignoring ./static/js/main.js where utility classes are toggled dynamically in the DOM.

To make the production build deterministic without bloating the runtime image:

  1. Added "./static/js/main.js" to the content array in tailwind.config.js.
  2. In the builder-base stage of Dockerfile.prod, installed Node.js, ran npm ci, and executed npx tailwindcss -i ./static/css/input.css -o ./static/css/output.css --minify immediately before collectstatic.
  3. Removed node_modules (rm -rf node_modules) before the final webapp stage copies /app from builder-base, keeping Node.js and npm packages out of the production container.

3. Standardized $APP_HOME, STATIC_ROOT, and Non-Root Ownership (Dockerfile, Dockerfile.prod, settings.py)

In the development Dockerfile, RUN mkdir $APP_HOME/staticfiles appeared before ENV APP_HOME=/app was defined and after chown -R appuser:appuser /app. Consequently, Docker expanded $APP_HOME to an empty string—creating /staticfiles at the root of the filesystem—and left any directories created at that step owned by root. Meanwhile, Dockerfile.prod set ENV APP_HOME=/app/django-app and settings.py set STATIC_ROOT = os.path.join(BASE_DIR, "django-app", "staticfiles"), creating a redundant /app/django-app/staticfiles path while MEDIA_ROOT sat at /app/mediafiles.

We standardized both Dockerfile and Dockerfile.prod on ENV APP_HOME=/app, updated STATIC_ROOT in settings.py to BASE_DIR / "staticfiles", and moved RUN mkdir -p $APP_HOME/staticfiles $APP_HOME/mediafiles prior to chown -R appuser:appuser /app so the non-root appuser owns both directories across environments.

4. Build Context Isolation (.dockerignore)

Without .venv/, node_modules/, staticfiles/, and mediafiles/ in django-app/.dockerignore, COPY . /app transferred host virtual environments (macOS binaries), local Node modules, and local media uploads into the Linux build context. Adding these four directories to .dockerignore shrinks the build context, prevents cross-OS binary conflicts, and keeps local test artifacts out of production images.

5. Compose Port Alignment, Anonymous Volume Masking, and Persistent Media (docker-compose.yml & docker-compose-prod.yml)

  • CSRF_TRUSTED_ORIGINS port match (docker-compose.yml): Because the development service maps host port 8080 to container port 8000 (8080:8000), browsers visiting http://localhost:8080 send Origin: http://localhost:8080 on POST requests. Updating CSRF_TRUSTED_ORIGINS from http://localhost:8000 to http://localhost:8080 resolves 403 Forbidden CSRF rejections on login, logout, and form submissions.
  • Protecting /app/node_modules from bind-mount shadowing (docker-compose.yml): Mounting ./django-app:/app in development overwrote /app/node_modules (built inside the container) with the host directory, breaking Supervisor's npx tailwindcss --watch process. Adding an anonymous volume (- /app/node_modules) preserves the container's internal node_modules directory over the bind mount.
  • Persistent media volume (docker-compose-prod.yml): Mounting a named volume media_data:/app/mediafiles ensures user-uploaded media files in MEDIA_ROOT persist across container recreations and deployments instead of vanishing with the container's ephemeral writable layer.

Questions

Knowledge check

  1. Question: Why does running python manage.py collectstatic --noinput --clear inside entrypoint.sh cause issues when static files are already collected during docker build?

    • Answer: --clear deletes the existing STATIC_ROOT contents before re-copying and re-hashing every file on every container restart. This adds unnecessary boot latency and creates a race condition during rolling restarts where live requests receive 404 Not Found while files are missing.
  2. Question: What happens in a Dockerfile if RUN mkdir -p $APP_HOME/staticfiles is placed before ENV APP_HOME=/app and after RUN chown -R appuser:appuser /app?

    • Answer: Because $APP_HOME is unset, Docker expands it to "" and creates /staticfiles at the filesystem root instead of /app/staticfiles. And because RUN executes as root until USER appuser is declared, creating directories after chown leaves them owned by root, causing PermissionError at runtime when appuser tries to write to them.
  3. Question: Why did POST requests to http://localhost:8080 fail with 403 Forbidden when CSRF_TRUSTED_ORIGINS was set to http://localhost:8000 in docker-compose.yml?

    • Answer: Django's CsrfViewMiddleware compares CSRF_TRUSTED_ORIGINS against the HTTP Origin header sent by the browser, which reflects the externally visible host and port (http://localhost:8080), not the internal container port (8000) to which Docker forwards the traffic.

Open questions

  • Should Gunicorn workers use --worker-class gthread (with --threads 2 or 4) in addition to --workers 3 so network I/O bound calls (such as external SMTP or API requests) release the thread while waiting on socket responses?
  • Should static files in production be served directly from an immutable object store / CDN or shared read-only volume with Nginx rather than from the application container filesystem?

References