Run Containers as a Non-Root User
By default a container runs as UID 0, and without a user namespace that is host root for many escape and volume paths. The fix is a numeric, explicit UID baked into the image plus a runtime refusal to run as root.
Procedure
- Create the user in the image with a fixed numeric UID (names are resolved in the image, so a bare
USER appfails on a base that lacks the passwd entry):RUN groupadd -g 10001 app && useradd -u 10001 -g 10001 -m -s /sbin/nologin app USER 10001:10001 chownthe working dir and any writable paths before switching, since root-only writes afterUSERfail:RUN chown -R 10001:10001 /app && chmod -R u+rwX /app.- At runtime, make the intent explicit and defensive:
docker run --user 10001:10001 --read-only --tmpfs /tmp app:x. - In Kubernetes set
runAsNonRoot: trueand a numericrunAsUser, which the kubelet refuses to violate:securityContext: runAsNonRoot: true runAsUser: 10001 allowPrivilegeEscalation: false capabilities: { drop: ["ALL"] } - Enforce cluster-wide with the Pod Security Standard
restrictedprofile, or a Kyverno rule requiringrunAsNonRoot: trueon every pod. - Check what a process can do:
docker run --rm app:x idmust printuid=10001. For ports, bind to>1024— non-root cannot bind80/443, so publish with-p 8080:8080and let the proxy handle the low port. - If a supervisor needs a low port, do not grant
CAP_NET_BIND_SERVICEbroadly; drop ALL and add back only that one capability.
Pitfalls
- Setting
USERin the Dockerfile does not stopdocker run --user 0; onlyrunAsNonRoot: truein the orchestrator enforces it. - A base image's
USER 1000is often overridden by a laterRUNthat escalates toUSER rootand never switches back — the image ships as root and nobody notices. chown -Rin a huge layer doubles image size; prefer creating files as the target user or--chown=10001:10001onCOPY.- Volume mounts from the host arrive owned by the host's UID; a container non-root user then cannot write them. Set
fsGroup(K8s) or--usermatching the host, or use an init container to chown. - Random UIDs from
runAsUserranges break images whose entrypoint reads/etc/passwdfor a home directory; mount a writableHOMEor an emptyDir instead. allowPrivilegeEscalation: falsestill permits a setuid binary already in the image — remove setuid bits in the Dockerfile (RUN find / -perm -4000 -exec chmod u-s {} +).
Verification
docker run --rm app:x id
# uid=10001(app) gid=10001(app) groups=10001(app)
The command prints a non-zero UID and the container runs its healthcheck without permission errors. Report the observed UID/GID and the policy that enforced it.