How to use non-root users in Docker?

· Category: Docker

Short answer

Use the USER instruction in a Dockerfile to run the container as a non-root user. Create the user with standard Linux commands and ensure file ownership matches.

Steps

  1. Create a group and user in the Dockerfile.
  2. Set appropriate ownership with --chown.
  3. Switch to the user with USER.
  4. Optionally specify the user at runtime with --user.

Example

FROM node:18-alpine
RUN addgroup -g 1001 -S nodejs && adduser -S nodeuser -u 1001
WORKDIR /app
COPY --chown=nodeuser:nodejs package*.json ./
RUN npm ci
COPY --chown=nodeuser:nodejs . .
USER nodeuser
CMD ["node", "server.js"]

Run as a different user:

docker run --user 1001:1001 myapp

Tips

  • Use fixed UIDs/GIDs to avoid host permission mismatches.
  • Some official images like node already provide a non-root user.
  • Kubernetes securityContext.runAsNonRoot enforces this at the orchestration layer.

Common issues

  • Permission denied errors occur if the user cannot read application files.
  • Binding to ports below 1024 requires root privileges.
  • Volume mounts may have host permissions that conflict with the container user.