Skip to main content

Docker Non-Root

Docker non-root is the practice of running a container's main process as an unprivileged user (UID above 0) instead of root. It limits what an attacker can do after exploiting the application.

Why root in a container matters

By default, containers run as root unless the image sets USER. Container isolation reduces the damage, but a root process holds more privileges and has a larger path to host impact if a kernel bug or misconfiguration allows escape. A non-root user cannot install packages, change system files, or use root-only features, and that is meaningful defense in depth.

Dockerfile patterns

Dockerfile
# Create a dedicated user (Alpine)
FROM node:20-alpine
WORKDIR /app
RUN addgroup -S appgroup && adduser -S appuser -G appgroup
COPY --chown=appuser:appgroup package.json package-lock.json ./
RUN npm ci --omit=dev
COPY --chown=appuser:appgroup dist/ ./dist/
USER appuser
EXPOSE 8080
CMD ["node", "dist/server.js"]
Dockerfile
# Use the node user that official Node images already include
FROM node:20-alpine
WORKDIR /app
COPY --chown=node:node . .
RUN npm ci --omit=dev
USER node
CMD ["node", "server.js"]

Verify

Bash
docker run --rm payment-api:v3.1.0 id
# uid=100(appuser) gid=101(appgroup)
docker inspect payment-api --format '{{.Config.User}}'

Writable paths

If the app writes logs or uploads, create those directories and set ownership while still root, before USER.

Dockerfile
RUN mkdir -p /app/uploads && chown -R node:node /app/uploads
USER node

You can also override at run time with docker run --user 1000:1000, or use rootless Docker so the daemon itself runs unprivileged.

Remember

USER applies to later instructions and to the running process. Put it after steps that need root and before CMD.

Security

Mounting /var/run/docker.sock makes non-root pointless, because Docker API access is effectively root on the host.

Frequently Asked Questions

Why run as non-root if namespaces already isolate containers?

Isolation is not a perfect boundary. Kernel bugs, extra capabilities, and risky mounts have enabled escapes, and a root process gets far more value from them. Non-root narrows what a successful exploit can do.

Why does my app crash after adding USER?

Usually a permissions problem. The new user cannot write to directories owned by root. Set ownership with chown or COPY --chown during the build, before switching users.

Can I bind to port 80 as a non-root user?

Not on privileged ports by default. Prefer listening on 8080 inside the container and publishing it as 80 on the host, or grant only NET_BIND_SERVICE if needed.

Found a mistake, an outdated step or a broken link?