Non-Root Container Filesystem Ownership and Persistent Media Volumes
Running a containerized web application as a non-root user (appuser) limits the blast radius of a container compromise, but requires strict coordination between Dockerfile instruction ordering, application directory paths (STATIC_ROOT, MEDIA_ROOT), persistent Docker volumes, and port-mapped CSRF_TRUSTED_ORIGINS.
1. ENV Declaration and chown Ordering in a Dockerfile
Every RUN instruction in a Dockerfile executes as root until a USER instruction switches the active UID/GID. Two subtle ordering bugs frequently break non-root containers:
- Referencing an undefined
ENVvariable: IfRUN mkdir $APP_HOME/staticfilesruns beforeENV APP_HOME=/appis declared, Docker substitutes an empty string for$APP_HOMEand creates/staticfilesat the root of the container filesystem (/) instead of/app/staticfiles. - Creating directories after
chown: IfRUN chown -R appuser:appuser /appruns beforeRUN mkdir -p $APP_HOME/staticfiles $APP_HOME/mediafiles, those newly created directories remain owned byroot:root. When the container starts asUSER appuser, any attempt to write toSTATIC_ROOTorMEDIA_ROOTfails withPermissionError: [Errno 13] Permission denied.
The correct sequence declares ENV APP_HOME=/app first, creates all required subdirectories, and only then transfers ownership before dropping privileges:
ENV APP_HOME=/app
WORKDIR $APP_HOME
# ... install dependencies & copy application code ...
RUN mkdir -p $APP_HOME/staticfiles $APP_HOME/mediafiles \
&& chown -R appuser:appuser $APP_HOME
USER appuser
2. Aligning STATIC_ROOT and MEDIA_ROOT Across Environments
When WORKDIR inside the container is /app (which is also Django's BASE_DIR), setting STATIC_ROOT = BASE_DIR / "django-app" / "staticfiles" while MEDIA_ROOT = BASE_DIR / "mediafiles" creates an inconsistent nested directory (/app/django-app/staticfiles) that diverges from the Dockerfile paths. Defining both relative to BASE_DIR keeps development and production paths identical:
STATIC_ROOT = BASE_DIR / "staticfiles"
MEDIA_ROOT = BASE_DIR / "mediafiles"
3. Persistent Named Volumes for MEDIA_ROOT in Production
Unlike compiled static files (which are baked into the immutable image layers at build time; see Multi-Stage Docker Builds for Frontend Assets and Static Collection), user-uploaded media files are written at runtime to MEDIA_ROOT (/app/mediafiles).
Without a volume mounted at /app/mediafiles in docker-compose-prod.yml, uploads are written to the container's ephemeral writable layer. Whenever the container is recreated (docker compose up -d --force-recreate or during an image upgrade), the writable layer is destroyed and all uploaded media files are permanently lost. Mounting a named volume persists uploads across deployments:
services:
web:
volumes:
- media_data:/app/mediafiles
volumes:
media_data:
4. Port-Mapped Containers and CSRF_TRUSTED_ORIGINS
Since Django 4.0, CsrfViewMiddleware validates the HTTP Origin header on unsafe requests (POST, PUT, DELETE) against CSRF_TRUSTED_ORIGINS, including the exact port number.
When a development docker-compose.yml maps host port 8080 to container port 8000 (ports: ["8080:8000"]), the browser accesses http://localhost:8080 and sends Origin: http://localhost:8080. If CSRF_TRUSTED_ORIGINS is set to the internal container port (http://localhost:8000), Django rejects every POST request with 403 Forbidden (Origin checking failed). CSRF_TRUSTED_ORIGINS must always list the externally visible scheme, host, and port (http://localhost:8080).
References
- Docker Docs: Dockerfile reference (
ENV,USER,VOLUME) - Variable expansion rules, privilege dropping withUSER, and how volumes inherit directory permissions. - Docker Docs: Volumes - Persisting runtime data outside the container's ephemeral writable layer.
- Django Documentation:
CSRF_TRUSTED_ORIGINS- Why non-default ports must be included in trusted origins forOriginheader validation. - Docker and Django Build and Runtime Hardening – Entrypoint, Multi-Stage Assets, and Compose Volumes - Lab fixing
$APP_HOME,STATIC_ROOT,media_datavolume, andCSRF_TRUSTED_ORIGINS. - Docker and Container Security MOC & Web Application and Django Security MOC - Domain hubs.
Review cards
Flashcard Why must `mkdir` for `staticfiles`/`mediafiles` run before `chown -R appuser:appuser $APP_HOME`?
Directories created after the chown are owned by root:root, so the app running as appuser gets Permission denied when it writes to them.
Flashcard What does `RUN mkdir $APP_HOME/staticfiles` create if `ENV APP_HOME=/app` comes later?
/staticfiles at the filesystem root: the undefined variable expands to an empty string.
Flashcard Why define both `STATIC_ROOT` and `MEDIA_ROOT` directly under `BASE_DIR`?
So they match the directories the Dockerfile creates and gives to appuser. BASE_DIR / "django-app" / "staticfiles" points to a nested /app/django-app/staticfiles instead.
Quiz With `ports: ["8080:8000"]` in development, which `CSRF_TRUSTED_ORIGINS` entry lets POSTs through?
-
http://localhost:8000 -
http://localhost:8080 -
http://localhost:8000/ -
http://localhost:8080/
Django compares the browser's Origin header (http://localhost:8080) with each entry exactly, port included, and an origin has no trailing slash.