Docker and Django Build and Runtime Hardening – Entrypoint, Multi-Stage Assets, and Compose Volumes
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:
entrypoint.shran withoutset -e, contained a brokennc -zdatabase wait loop referencing undefined environment variables (DATABASE,SQL_HOST,SQL_PORT) withoutnetcatinstalled in the image, re-rancollectstatic --clearon every production container restart, and launched Gunicorn with its default single synchronous worker (1worker,30stimeout, no stdout access logs).Dockerfile.prodrancollectstaticwithout compiling Tailwind CSS, relying on whateverstatic/css/output.cssexisted on the host, whiletailwind.config.jsomitted./static/js/main.jsfrom itscontentscan.Dockerfilereferenced$APP_HOMEbefore defining it (causingRUN mkdir $APP_HOME/staticfilesto create/staticfilesat the filesystem root asrootafterchown), whileDockerfile.prodandsettings.pynestedSTATIC_ROOTunder/app/django-app/staticfileswhileMEDIA_ROOTlived at/app/mediafiles..dockerignoredid not exclude.venv/,node_modules/,staticfiles/, ormediafiles/, allowing host macOS virtualenvs and Node binaries to leak intoCOPY . /app.- Development and production Compose files had port, volume, and mount gaps:
CSRF_TRUSTED_ORIGINSindocker-compose.ymlwas set tohttp://localhost:8000despite the container publishing8080:8000; the./django-app:/appbind mount shadowed the image's/app/node_modules; anddocker-compose-prod.ymllacked a persistent volume for/app/mediafiles.
Key ideas
- Fail-fast container entrypoints (
set -e): Withoutset -e, a failedpython3 manage.py migratedoes 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 -zloops break silently when variable names drift or whennetcatis stripped from minimal images. Docker Compose'sdepends_onwithcondition: service_healthydelegates readiness checks to the database container's native healthcheck. - Build-time vs. runtime static asset collection: When
collectstaticis already executed duringdocker build, runningcollectstatic --noinput --clearinsideentrypoint.shon every restart deletes and re-hashes the static directory at runtime—adding startup latency and causing transient404responses 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 todocker logs. - Self-contained multi-stage asset builds: Installing Node.js, running
npm ci, and compiling minified Tailwind CSS (npx tailwindcss ... --minify) in thebuilder-basestage beforecollectstatic—then deletingnode_modulesprior to copying/appinto 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 intailwind.config.jscontentso those classes are not purged during production minification. - Non-root directory creation and
chownordering: In aDockerfile,ENV APP_HOME=/appmust be declared beforeRUN mkdir -p, and all directory creation must happen beforechown -R appuser:appuser /appandUSER appuserto avoid root-owned directories and runtimePermissionErrorexceptions. - Build context isolation and anonymous volume masking: Excluding
.venv/andnode_modules/in.dockerignoreprevents host-OS binary collisions duringdocker build, while an anonymous volume (- /app/node_modules) in developmentdocker-compose.ymlprevents a host bind mount (./django-app:/app) from overwriting the container's Linuxnode_modules. - Origin port alignment and persistent media storage:
CSRF_TRUSTED_ORIGINSmust match the host-mapped port (http://localhost:8080for8080:8000) that the browser sends in theOriginheader, and productionMEDIA_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_PORTwait loop: NeitherDATABASE,SQL_HOST, norSQL_PORTexisted in.env(which usesPOSTGRES_HOSTandPOSTGRES_PORT), andnetcatwas not installed in the image. SettingDATABASE=postgreswould have trapped the container in an infinitenc: not foundloop. Container startup ordering is already enforced by Docker Compose'sdepends_on: db: condition: service_healthy. - Runtime
collectstatic --noinput --clear: Because static assets are baked into the image during theDockerfile.prodbuild 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:
- Added
"./static/js/main.js"to thecontentarray intailwind.config.js. - In the
builder-basestage ofDockerfile.prod, installed Node.js, rannpm ci, and executednpx tailwindcss -i ./static/css/input.css -o ./static/css/output.css --minifyimmediately beforecollectstatic. - Removed
node_modules(rm -rf node_modules) before the finalwebappstage copies/appfrombuilder-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_ORIGINSport match (docker-compose.yml): Because the development service maps host port8080to container port8000(8080:8000), browsers visitinghttp://localhost:8080sendOrigin: http://localhost:8080onPOSTrequests. UpdatingCSRF_TRUSTED_ORIGINSfromhttp://localhost:8000tohttp://localhost:8080resolves403 ForbiddenCSRF rejections on login, logout, and form submissions.- Protecting
/app/node_modulesfrom bind-mount shadowing (docker-compose.yml): Mounting./django-app:/appin development overwrote/app/node_modules(built inside the container) with the host directory, breaking Supervisor'snpx tailwindcss --watchprocess. Adding an anonymous volume (- /app/node_modules) preserves the container's internalnode_modulesdirectory over the bind mount. - Persistent media volume (
docker-compose-prod.yml): Mounting a named volumemedia_data:/app/mediafilesensures user-uploaded media files inMEDIA_ROOTpersist across container recreations and deployments instead of vanishing with the container's ephemeral writable layer.
Questions
Knowledge check
-
Question: Why does running
python manage.py collectstatic --noinput --clearinsideentrypoint.shcause issues when static files are already collected duringdocker build?- Answer:
--cleardeletes the existingSTATIC_ROOTcontents 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 receive404 Not Foundwhile files are missing.
- Answer:
-
Question: What happens in a
DockerfileifRUN mkdir -p $APP_HOME/staticfilesis placed beforeENV APP_HOME=/appand afterRUN chown -R appuser:appuser /app?- Answer: Because
$APP_HOMEis unset, Docker expands it to""and creates/staticfilesat the filesystem root instead of/app/staticfiles. And becauseRUNexecutes asrootuntilUSER appuseris declared, creating directories afterchownleaves them owned byroot, causingPermissionErrorat runtime whenappusertries to write to them.
- Answer: Because
-
Question: Why did
POSTrequests tohttp://localhost:8080fail with403 ForbiddenwhenCSRF_TRUSTED_ORIGINSwas set tohttp://localhost:8000indocker-compose.yml?- Answer: Django's
CsrfViewMiddlewarecomparesCSRF_TRUSTED_ORIGINSagainst the HTTPOriginheader 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.
- Answer: Django's
Open questions
- Should Gunicorn workers use
--worker-class gthread(with--threads 2or4) in addition to--workers 3so 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
- GNU Bash Manual: The Set Builtin (
set -e) - Specification ofset -e(errexit) for aborting shell scripts when a command exits with a non-zero status. - Gunicorn Documentation: Settings (
workers,timeout,accesslog) - Default values (workers = 1,timeout = 30,accesslog = None) and configuration flags for worker processes and logging. - Docker Docs: Multi-stage builds - Building assets in an intermediate stage and copying only compiled artifacts into the final runtime image.
- Docker Docs:
.dockerignorefiles - Excluding host directories (.venv,node_modules) from the build context sent to the Docker daemon. - Django Documentation:
CSRF_TRUSTED_ORIGINS- Origin header validation for cross-origin and port-mapped unsafe (POST) requests since Django 4.0.