Sub topic 13
Running as a non-root user
This chapter assumes you can read a multi-stage Dockerfile, that you know FROM ... AS and COPY --from, and that you can run docker build and docker run. By the end you will know why a container should not run as root, how to set a user in each kind of final image, and how to fix the permission errors that follow.
Why root in a container is a risk
By default, the process inside a container runs as user ID 0, which is root. Container isolation is real, but it is not a perfect wall. If an attacker exploits your app, a root process gives them more to work with:
- They can write anywhere in the container filesystem, including the app's own code.
- They can install tools with the package manager, if the image still has one.
- They get more room to attack the container runtime through a kernel or runtime bug. Such bugs are rare, but a container escape that starts from root is worse than one that starts from an unprivileged user.
- Any bind-mounted host directory can be written as root. Files created there end up owned by root on the host.
Many platforms enforce the rule for you. Kubernetes clusters with a restricted Pod Security policy, or pods that set runAsNonRoot: true, refuse to start an image that would run as root.
A non-root user does not make an app secure. It limits the damage after a compromise, which is why it is cheap protection worth always adding.
The USER instruction
USER sets the user for all later RUN, CMD and ENTRYPOINT instructions, and for the running container. It accepts a name or a numeric ID, optionally followed by a group (USER 10001:10001).
Two details matter for ordering:
- Instructions before
USERstill run as root. That is what you want forapt-get installornpm ci. USERdoes not change who owns files. Files added byCOPYbelong to root unless you say otherwise.
The usual pattern is to do all the privileged work first, then drop privileges as the last step before CMD.
Since the diagram must use the required fence, here it is in the correct form:
Users that already exist in common images
You often do not need to create a user.
| Base image | Existing unprivileged user | Notes |
|---|---|---|
| `node` and `node:*-slim` | `node` (UID 1000) | Used in the Node.js example in this tutorial: `USER node`. |
| `python:*-slim` | none by default, but `nobody` (UID 65534) exists | `USER nobody` works but shares an identity with other system tasks. |
| Debian and Ubuntu based images | `nobody` | Same as above. |
| Alpine | `nobody` | Same as above. |
| Distroless | `nonroot` (UID 65532) via the `:nonroot` tag | The default tag runs as root, so pick the `nonroot` variant. |
| `scratch` | none | There is no `/etc/passwd` at all. |
A dedicated user is better than nobody when you have a choice. A named service user gives you stable file ownership and avoids sharing an identity with anything else on the system.
Creating a user
On Debian-based images, use groupadd and useradd. Set an explicit numeric ID so the user is the same across rebuilds and so orchestrators can verify it.
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
CMD ["python", "app.py"]On Alpine, the BusyBox tools use different flags:
FROM alpine:3.20
RUN addgroup -g 10001 -S app \
&& adduser -S -u 10001 -G app -H app
WORKDIR /app
COPY --chown=app:app . .
USER app
CMD ["/app/run.sh"]Both files create the user in a single RUN, which keeps the layer count down. The shell is set to nologin or left minimal because nobody should ever log in to this account.
File ownership and COPY --chown
Files copied into the image are owned by root, and a non-root app can read most of them but not write to them. For code that is the right outcome, since an app that cannot modify its own code is harder to tamper with. Problems show up only when the app needs to write somewhere, such as a cache, an upload folder or a SQLite file.
Give the user ownership at copy time:
COPY --chown=app:app . .Do not do this instead:
COPY . .
RUN chown -R app:app /appThe second form works, but chown rewrites every file into a new layer. The old copies still sit in the layer below, so the image gets larger. This is the layer-size problem from earlier chapters. COPY --chown sets ownership as the file is written, with no extra layer. It also works with COPY --from=build:
COPY --from=build --chown=node:node /app/dist ./distFor directories that only need to exist and be writable, create them as root and hand them over before dropping privileges:
RUN mkdir -p /app/data && chown app:app /app/dataKeep this to the small directory that needs it, not the whole application tree.
A non-root user on scratch
A scratch image has no /etc/passwd, so there is no user name to look up. You can still use a numeric ID, because USER accepts one without checking it against any file. Docker simply starts the process with that UID and GID.
This extends the Go example from earlier in the tutorial:
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/app .
FROM scratch
COPY --from=build /out/app /app
USER 10001:10001
ENTRYPOINT ["/app"]The binary produced by go build has mode 755, so any user can execute it. If your build produced a file that was readable only by root, the container would fail with permission denied at start.
The app itself will see UID 10001, but anything that looks up the name will find nothing. Some programs call getpwuid at startup and fail when the lookup returns nothing. If yours does, copy a minimal passwd file from the build stage. Create it there first, because scratch has no tools:
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /out/app . \
&& echo "app:x:10001:10001::/:/sbin/nologin" > /out/passwd
FROM scratch
COPY --from=build /out/passwd /etc/passwd
COPY --from=build /out/app /app
USER 10001:10001
ENTRYPOINT ["/app"]If you prefer not to maintain this, use a distroless :nonroot image. It already contains the nonroot user and CA certificates.
Checking which user is running
Verify the result instead of trusting the Dockerfile. For images that contain an id command, override the entrypoint:
docker build -t myapp:nonroot .
docker run --rm --entrypoint id myapp:nonroot
docker inspect --format '{{.Config.User}}' myapp:nonrootThe first command prints the UID and GID the process would run as. The second prints the USER value stored in the image metadata. For scratch images, only the second works, since there is no id binary to run.
Common problems
- Permission denied on write. The app writes to a directory owned by root. Create the directory and
chownit beforeUSER, or useCOPY --chown. Do not solve it by going back to root. - Permission denied on a bind mount or volume. A bind mount takes the host directory's ownership, so the container UID must match or the host directory must be changed. A new named volume copies the ownership of the image directory it mounts over, so fix ownership in the image first.
- Cannot bind to port 80 or 443. Ports below 1024 are privileged on many systems. Docker Engine lowers this limit inside containers, but other runtimes may not. Listen on a high port such as 8080 and map it:
-p 80:8080. - Package installs fail after USER.
apt-get,apk addandpip installinto system paths need root. Put them beforeUSER. - USER placed too early. If
USER appcomes beforenpm ciin the same stage, installs may fail, or the cache directories end up owned by the wrong user. - Orchestrator rejects a name. Kubernetes
runAsNonRootcannot verify a user name such asapp, because it cannot read the image's passwd file. Use a numericUSER, as shown above.
Summary
- Run the final container as an unprivileged user so a compromised app has less power.
- Do privileged work first, then drop privileges with
USERas the last step beforeCMD. - Use the
nodeuser,nobody, or a created user with a fixed numeric ID. Inscratch, a numericUSERalone is enough. - Use
COPY --chownto set ownership without growing the image. - Confirm the result with
docker inspectanddocker run --entrypoint id.
Exercise
A multi-stage Dockerfile ends with COPY --from=build /app/dist ./dist, then RUN chown -R app:app /app, then USER app. The image is larger than expected, and an app that writes to /app/dist/cache still works. What is wrong with the size, and how do you fix it without breaking the write access?
Show answer
The RUN chown -R rewrites every file under /app into a new layer, so the earlier root-owned copy stays in the layer below and the image carries both. Replace the copy and the chown with COPY --from=build --chown=app:app /app/dist ./dist, which sets ownership while the files are written and adds no extra layer. The app keeps write access because the files are owned by app.
Exercise
Your final stage is FROM scratch with USER 10001:10001. The container starts, but the app exits at startup with an error from a user lookup. Name two ways to fix it, and name the command that shows which user the image is configured to run as.
Show answer
Either create a minimal /etc/passwd entry for UID 10001 in the build stage and copy it into scratch with COPY --from=build, or switch the final stage to a distroless :nonroot image, which already includes the nonroot user. Run docker inspect --format '{{.Config.User}}' IMAGE to see the configured user. docker run --entrypoint id does not work here because scratch has no id binary.