11.2.1 Non Root Runtime
A focused guide to Non Root Runtime, connecting core concepts with practical Docker and container operations.
Non-root runtime means a container's main process runs as a regular, unprivileged user rather than as root, meaningfully limiting what a compromised process inside the container could actually do, even within the boundaries of that container's own namespace.
Why Running as Root by Default Is a Meaningful Risk
Without an explicit USER instruction, a container's process runs as root by default, granting it broader privileges within the container than most applications actually need.
FROM node:20-alpine
COPY . /app
CMD ["node", "/app/server.js"]
Without an explicit non-root user, this application runs as root inside its container, an unnecessarily broad default for an application that has no genuine need for root privileges.
Specifying a Non-Root User
Creating and switching to a dedicated, unprivileged user is a straightforward addition to most Dockerfiles.
FROM node:20-alpine
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
COPY . /app
USER appuser
CMD ["node", "/app/server.js"]
This application now runs as appuser, a regular user without root privileges, rather than as root.
Why Many Official Images Already Provide a Non-Root User
Several official images include a pre-created, non-root user specifically intended for this purpose, simplifying adoption of this practice.
FROM node:20-alpine
USER node
The node image's official variant includes a pre-created node user, ready to be used without needing to create one manually.
Verifying the Container Actually Runs as Non-Root
Confirming the actual running user inside a container validates this configuration is correctly in effect.
docker exec myapp whoami
Why Non-Root Runtime Matters
Running as a non-root user by default meaningfully limits the potential impact of a compromised application process, since many actions that would be possible as root are simply unavailable to an unprivileged user, providing an important layer of defense even if other security measures somehow fail.