Sub topic 6
Running Your Application as a Non-Root User
This chapter assumes you can write a Dockerfile, run containers, and read Linux file permissions (owner, group, mode bits). It also assumes you know what a UID is. By the end you will be able to run an application as an unprivileged user, fix the permission errors that follow, and check the result.
Why root inside a container is a problem
By default, the process in a container runs as UID 0, which is root. Container isolation (namespaces, cgroups, capabilities) limits what that root user can do. Isolation is not perfect, though, because the container shares the host kernel. If an attacker escapes through a kernel bug, a runtime flaw, or a bad mount, a process that was UID 0 in the container is often UID 0 on the host.
Running as non-root helps in three ways:
- Less damage from application bugs. A remote code execution flaw gives the attacker only the privileges of the application user.
- Fewer escape paths. Many container escapes need root to exploit, such as writing to host-mounted paths or using
CAP_SYS_ADMIN. - Safer mounts. A bind-mounted host directory is only writable if the container user has the matching permissions on the host.
Non-root does not make a container safe by itself. It is one layer. Later chapters cover dropped capabilities, read-only filesystems, and user namespace remapping, which work with it.
How the USER instruction works
The USER instruction sets the user for the rest of the build stage and for the container's runtime process. Instructions that come after it (RUN, CMD, ENTRYPOINT) run as that user.
You can give a name or a number:
USER appuser
USER 10001
USER 10001:10001A numeric UID is the safer choice. A name must exist in the image's /etc/passwd, and some policy tools cannot verify that a name is non-root. Kubernetes runAsNonRoot, for example, rejects a non-numeric user because it cannot prove the name maps to a non-zero UID. Using a number also works in minimal images that have no useradd command.
Choose a UID above 10000. Low UIDs often collide with host system accounts. If a volume or user namespace maps the container UID to the host, a collision could give the process the rights of a real host service.
Creating the user
How you create the user depends on the base image.
Debian and Ubuntu images
# syntax=docker/dockerfile:1
FROM python:3.12-slim
RUN groupadd --gid 10001 app \
&& useradd --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app
WORKDIR /app
COPY --chown=app:app . .
USER app:app
CMD ["python", "main.py"]--no-create-home avoids an unneeded directory, and --shell /usr/sbin/nologin means nobody can use the account for an interactive login.
Alpine images
Alpine uses BusyBox tools with different flags:
# syntax=docker/dockerfile:1
FROM alpine:3.20
RUN addgroup -g 10001 -S app \
&& adduser -u 10001 -S -G app -H -s /sbin/nologin app
USER 10001:10001
CMD ["sleep", "3600"]-S creates a system account, and -H skips the home directory.
Images that already provide a user
Some images ship a non-root user. The official node image has node (UID 1000). Distroless images have nonroot (UID 65532). Use them when they exist:
# syntax=docker/dockerfile:1
FROM node:20-slim
WORKDIR /app
COPY --chown=node:node . .
USER node
CMD ["node", "server.js"]The multi-stage example from the Topic Spine earlier in this tutorial ends with FROM gcr.io/distroless/static-debian12:nonroot and USER nonroot:nonroot. The :nonroot tag already sets this user, and repeating USER makes the intent clear to readers and to linters.
Where to put USER
Put USER after the steps that need root, such as installing packages, and before the final CMD. Everything installed as root stays root-owned, which is usually what you want. The application can read its code but cannot change it.
# syntax=docker/dockerfile:1
FROM python:3.12-slim
# Root steps first
RUN apt-get update \
&& apt-get install -y --no-install-recommends libpq5 \
&& rm -rf /var/lib/apt/lists/*
RUN groupadd --gid 10001 app \
&& useradd --uid 10001 --gid app --no-create-home app
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Code stays root-owned and read-only to the app user
COPY . .
# Only the data directory is writable by the app
RUN mkdir /data && chown app:app /data
USER 10001:10001
CMD ["python", "main.py"]Leaving the code root-owned is a deliberate choice. If an attacker takes over the application, they cannot overwrite your source files. Use COPY --chown only for files the application must modify.
Fixing permission errors
Switching to non-root commonly breaks an application at startup. These are the usual causes.
| Symptom | Cause | Fix |
|---|---|---|
| `EACCES` writing to `/app/logs` | Directory is root-owned | Create it and `chown` it in the Dockerfile, or log to stdout |
| `bind: permission denied` on port 80 | Ports below 1024 need `CAP_NET_BIND_SERVICE` | Listen on 8080 and map it with `-p 80:8080` |
| Cannot write to a named volume | Volume was created with root ownership | `chown` the path in the image before the volume is first used |
| Cannot write to a bind mount | Host directory UID does not match the container UID | `chown` the host directory to the container UID |
| `HOME` not writable | The user has no home directory | Set `HOME=/tmp` or create a home directory |
| Tool writes cache files and fails | Cache path defaults to a root-only location | Point the cache to `/tmp` through an environment variable |
Ports below 1024
The simplest fix is to move the application to a high port and let Docker map it:
docker run -d --user 10001:10001 -p 80:8080 myapp:1.0The host side of -p is handled by the Docker daemon, not by the container process, so the container user does not need privileges for port 80. If you must bind a low port inside the container, you can add back a single capability with --cap-add NET_BIND_SERVICE, but a high port is better.
Named volumes
When Docker first mounts an empty named volume at a path that exists in the image, it copies the image's content and ownership into the volume. So set ownership in the image first:
# syntax=docker/dockerfile:1
FROM debian:12-slim
RUN groupadd --gid 10001 app \
&& useradd --uid 10001 --gid app --no-create-home app \
&& mkdir /data && chown app:app /data
VOLUME /data
USER 10001:10001
CMD ["sh", "-c", "echo ok > /data/test && cat /data/test"]Ownership is copied only the first time. A volume that already exists keeps its old ownership, so you may need to remove and recreate it.
Bind mounts
Bind mounts use the host's ownership and do not copy anything. If the host directory belongs to UID 1000 and the container runs as 10001, writes fail. Fix it on the host:
sudo chown -R 10001:10001 ./data
docker run --rm --user 10001:10001 -v "$PWD/data:/data" myapp:1.0Avoid chmod 777 as a shortcut. It lets any user on the host write to the directory.
Overriding the user at run time
docker run --user overrides the USER instruction. This is useful for images that run as root by default and that you cannot rebuild:
docker run --rm --user 10001:10001 alpine:3.20 idThe output is uid=10001 gid=10001. The user need not exist in /etc/passwd. The process simply has that numeric identity. This can still break images that expect to write to root-owned paths.
You can also set it in Compose:
services:
web:
image: myapp:1.0
user: "10001:10001"Checking the result
Do not trust the Dockerfile alone. Verify on the running container:
docker run -d --name web myapp:1.0
docker exec web id
docker exec web ps -o user,pid,comm
docker inspect --format '{{.Config.User}}' webdocker exec web id shows the effective UID. An empty Config.User means the container runs as root. You can also check an image without starting it:
docker image inspect --format '{{.Config.User}}' myapp:1.0Linters such as Hadolint warn when a Dockerfile has no USER instruction, and image scanners flag images that run as root. Put one of them in your CI pipeline.
The process tree: entrypoints and root helpers
Some images start as root on purpose, run a setup script, and then drop privileges. The official postgres and redis images do this with gosu or su-exec. The entrypoint fixes ownership of the data directory as root and then runs the server as an unprivileged user.
This pattern is acceptable when:
- the root phase is short and does only setup,
- the final long-running process is non-root, and
- you combine it with
--cap-drop ALLand add back only what setup needs, such asCHOWN,SETUID, andSETGID.
Prefer a fully non-root image when you can. If you write your own entrypoint, use exec so the application replaces the shell and receives signals directly:
#!/bin/sh
set -e
exec "$@"setuid binaries and escalation
A non-root process can sometimes become root by running a setuid binary such as su or sudo. Reduce the risk in two ways:
- Remove setuid bits you do not need in the image, with
find / -perm /6000 -type f -exec chmod a-s {} +in aRUNstep. - Start the container with
--security-opt no-new-privileges, which blocks setuid escalation at run time.
Do not install sudo in an application image.
A note on user namespaces and rootless mode
Running the process as non-root inside the container is separate from user namespace remapping and rootless Docker. Those features change what UID 0 means on the host. A later chapter covers them. Use them in addition to a non-root USER, not instead of it.
Common mistakes
- Putting
USERbeforeRUN apt-get install, which then fails because the user cannot install packages. - Using
COPY --chownon the whole application tree, which makes the code writable by the application. - Forgetting that
WORKDIRcreates the directory as root, so the app user cannot write there. - Relying on
USERin the image while the deployment forces--user 0. - Using
chmod -R 777to hide an ownership problem.
Exercise
A container built with USER 10001:10001 fails at startup with "permission denied" when it tries to bind to port 443 inside the container. Name two ways to fix this and say which you prefer.
Show answer
Option one: change the application to listen on a high port such as 8443 and publish it with -p 443:8443. Option two: keep port 443 and add back only the needed capability with --cap-drop ALL --cap-add NET_BIND_SERVICE. The first is preferred because it needs no extra capability, so the container keeps the smallest privilege set.
Exercise
You mount a host directory with -v "$PWD/data:/data" into a container running as UID 10001. The app gets "permission denied" writing to /data. The directory is owned by UID 1000 with mode 755. What is the cause, and what is a safe fix?
Show answer
Bind mounts keep the host's ownership, and mode 755 gives write access only to the owner (UID 1000). UID 10001 falls under "other" and can only read. The safe fix is sudo chown -R 10001:10001 ./data on the host. Do not use chmod 777, because that lets every host user write to the directory.
Exercise
How can you check, without entering the container, whether a running container named web is running as root?
Show answer
Run docker inspect --format '{{.Config.User}}' web. An empty result or 0 or root means root. To see the actual effective identity of the process, run docker exec web id.