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
# Create a dedicated user (Alpine)FROM node:20-alpineWORKDIR /appRUN addgroup -S appgroup && adduser -S appuser -G appgroupCOPY --chown=appuser:appgroup package.json package-lock.json ./RUN npm ci --omit=devCOPY --chown=appuser:appgroup dist/ ./dist/USER appuserEXPOSE 8080CMD ["node", "dist/server.js"]# Use the node user that official Node images already includeFROM node:20-alpineWORKDIR /appCOPY --chown=node:node . .RUN npm ci --omit=devUSER nodeCMD ["node", "server.js"]Verify
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.
RUN mkdir -p /app/uploads && chown -R node:node /app/uploadsUSER nodeYou can also override at run time with docker run --user 1000:1000, or use rootless Docker so the daemon itself runs unprivileged.
Remember
USERapplies to later instructions and to the running process. Put it after steps that need root and beforeCMD.
SecurityMounting
/var/run/docker.sockmakes 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.