Sub topic 12
Running as a non-root user
This chapter assumes you can write a basic Dockerfile with FROM, COPY, RUN, and CMD, and that you can build and run an image. You should also know that a container is an isolated process on the host, not a virtual machine.
Why root in a container is a problem
By default, the process in a container runs as root (user ID 0). Root inside a container is not the same as root on the host, because namespaces and dropped capabilities limit what it can do. It is still a poor default.
- A bug in your app, such as a path traversal or remote code execution, gives the attacker root-level file access inside the container.
- Files written to a bind-mounted host directory end up owned by UID 0 on the host.
- If a container escape vulnerability exists, a process that is already root has a shorter path to host root.
- Many security scanners and cluster policies, such as Kubernetes Pod Security Standards, flag or reject containers that run as root.
Running as a non-root user is cheap and removes much of this risk. It does not replace other controls such as read-only filesystems and dropped capabilities, but it is the first step.
How the USER instruction works
USER sets the user (and optionally the group) for every instruction after it in the same stage. This includes later RUN commands and the final CMD or ENTRYPOINT at runtime.
USER appuser
USER appuser:appgroup
USER 10001:10001The user can be a name or a numeric ID. A name must exist in the image's /etc/passwd. A numeric ID does not need an entry, so it works in minimal images that have no user database.
USER only changes who runs things. It does not change who owns files. Files copied with COPY are owned by root unless you say otherwise. This is the source of most non-root errors.
Pattern 1: use the user that ships with the image
Many official images already include an unprivileged user. The node images include a user named node with UID 1000. This is why the Dockerfile in this tutorial can end with USER node without creating anything.
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --chown=node:node . .
ENV NODE_ENV=production
EXPOSE 3000
USER node
CMD ["node", "server.js"]Compared with the earlier version, COPY --chown=node:node . . gives the node user ownership of the source files. Without it, the files are owned by root. The app can usually still read them, because they are world-readable. It cannot write to them, which matters if the app creates caches or temporary files in /app.
Check which user an image or container uses:
docker run --rm myapp:1.0 idThe output shows uid=1000(node) gid=1000(node). The command overrides CMD, so it runs id in place of the server, but it still uses the image's USER.
Pattern 2: create your own user
If the base image has no suitable user, create one in a RUN step before USER. The command differs between Debian-based and Alpine-based images.
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 requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY --chown=app:app . .
USER app
CMD ["python", "main.py"]On Alpine, groupadd and useradd are not available by default. Use BusyBox's addgroup and adduser instead:
FROM alpine:3.20
RUN addgroup -g 10001 -S app \
&& adduser -u 10001 -S -G app -H -s /sbin/nologin app
USER appA few choices in these commands are deliberate:
- A fixed UID and GID (here 10001) makes behavior predictable. Volume permissions and Kubernetes
runAsUsersettings refer to numbers, not names. - A high UID avoids collisions with real users on a host that shares a bind mount.
--no-create-homeand anologinshell reduce what the account can do. A service account does not need to log in.
Pattern 3: distroless and numeric users
Distroless images contain only the app's runtime dependencies. They have no shell and no package manager, so you cannot run useradd in them. They provide ready-made variants instead. The multi-stage Go example from earlier uses one:
FROM golang:1.22 AS build
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -o /out/app .
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=build /out/app /app
ENTRYPOINT ["/app"]The :nonroot tag sets the default user to UID 65532. You do not need a USER line, though adding USER 65532:65532 makes the intent visible to a reader.
If you build on scratch, there is no /etc/passwd at all. A numeric USER 10001:10001 still works, because Docker does not need a name to run a process as that ID.
Order matters: do privileged work before USER
Instructions that need root, such as installing packages, must come before USER. After USER, a RUN apt-get install fails with a permission error.
FROM debian:12-slim
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates \
&& rm -rf /var/lib/apt/lists/*
RUN useradd --uid 10001 --create-home app
USER app
WORKDIR /home/appYou can also switch back with a second USER root and then return to the unprivileged user. This works, but it makes the file harder to audit. A better approach is to keep all root work at the top of the stage and place a single USER near the end.
In a multi-stage build, USER applies per stage. Setting it in the build stage has no effect on the final stage, which starts fresh from its own FROM. Set it in the stage that produces the image you run.
Ownership and permissions
Four situations cause most permission errors.
Files copied as root
COPY and ADD create files owned by root. Use --chown to set the owner at copy time. This is better than a separate RUN chown -R, which creates a new layer that duplicates every changed file and increases image size.
COPY --chown=app:app . /appWORKDIR creates a missing directory owned by root too. If the app writes to a directory, create it with the right owner first:
RUN mkdir /data && chown app:app /data
VOLUME /dataSet ownership before declaring VOLUME. Changes made to a path after it is declared as a volume are discarded in the build.
Binding to low ports
Non-root processes cannot bind to ports below 1024 on most systems by default. A server that listens on port 80 fails with permission denied. Listen on a high port such as 8080 or 3000 in the container and map it at runtime:
docker run --rm -p 80:8080 myapp:1.0EXPOSE documents the container port. The -p flag controls what the host publishes, so the app itself never needs port 80.
Bind mounts and volumes
With a bind mount, the host directory keeps its host ownership. If the host directory is owned by UID 1000 and the container runs as UID 10001, writes fail. Fix this by matching the IDs, or run with a chosen user for development:
docker run --rm --user "$(id -u):$(id -g)" -v "$PWD/out:/out" myapp:1.0A named volume is different. Docker copies the ownership of the image's directory into a new, empty named volume on first use. That is why the chown before VOLUME matters.
Writing to the home directory or `/tmp`
Tools often write to $HOME, such as caches for npm or pip. A user created with --no-create-home has no writable home. Either create one, or point the cache somewhere writable with an environment variable such as npm_config_cache=/tmp/.npm.
Overriding the user at runtime
docker run --user overrides the image's USER. This is useful for testing and for debugging as root:
docker run --rm --user root myapp:1.0 idThe override works in both directions. A platform that runs containers with an arbitrary UID, such as OpenShift, ignores your USER and assigns a random one in the root group (GID 0). To support it, make writable directories group-writable for GID 0:
RUN mkdir /app/cache && chgrp -R 0 /app/cache && chmod -R g=u /app/cacheChecking your result
Build the image and confirm what it runs as. docker inspect shows the configured user:
docker build -t myapp:1.0 .
docker inspect --format '{{.Config.User}}' myapp:1.0
docker run --rm myapp:1.0 id -uAn empty value from inspect means the image runs as root. The second command should print a number other than 0. If your image has no shell or id binary, such as a distroless one, rely on inspect and on checking the process from the host with docker top.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `EACCES` or `Permission denied` writing under `/app` | Files owned by root | Use `COPY --chown`, or create writable directories before `USER` |
| `apt-get` or `apk` fails after `USER` | Install step placed after the switch | Move package installs above `USER` |
| `bind: permission denied` on port 80 | Non-root cannot use ports below 1024 | Listen on 8080 and publish with `-p 80:8080` |
| `unable to find user app` | User was never created in this stage | Create the user in the same stage that sets `USER` |
| Image is larger after adding `chown` | `RUN chown -R` duplicated files in a new layer | Use `COPY --chown` instead |
| Pod rejected by `runAsNonRoot` | `USER` is a name, not a number | Use `USER 10001` |
Exercise
A Dockerfile ends with USER app, and the app crashes with EACCES: permission denied, mkdir '/app/logs'. The source was added with COPY . /app. Give two ways to fix it, and say which one avoids adding image size.
Show answer
Use COPY --chown=app:app . /app so the files are owned by app, or create the directory before the user switch with RUN mkdir /app/logs && chown app:app /app/logs. Both work. COPY --chown adds no extra layer, while a separate RUN chown -R app:app /app copies every changed file into a new layer and enlarges the image. The narrow mkdir plus chown on a single empty directory adds almost nothing.
Exercise
You build FROM scratch and copy in a static binary. You want it to run as UID 10001. Why does USER 10001:10001 work even though the image has no /etc/passwd, and why would USER app fail?
Show answer
Docker can start a process with a numeric UID and GID without looking anything up. A name like app must be resolved through /etc/passwd, which does not exist in a scratch image, so the container fails to start with an error that the user cannot be found.