Run as user

2 snippets in Docker

DKDocker

USER - Set Runtime User

DK · Dockerfile
Syntax
USER <username>[:<group>]
Example
RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser
USER appuser

Note All subsequent RUN, CMD, and ENTRYPOINT instructions run as this user. Running as root in production is a security risk - always create and switch to a non-root user for the final stage.

Run as Non-Root User

DK · Best Practices
Syntax
RUN addgroup --system appgroup && adduser --system --ingroup appgroup appuser
USER appuser
Example
FROM node:20-alpine
WORKDIR /app
COPY --chown=node:node . .
RUN npm ci --omit=dev
USER node
CMD ["node", "server.js"]

Note Node images ship with a built-in 'node' user. Many images include a non-root user - check the docs before creating your own. Running as root inside a container means a container escape could grant host-level root access.

Frequently asked questions

How do you run as user?
Docker covers this with 2 copy-ready snippets on this page. The "USER - Set Runtime User" snippet in Docker uses `USER <username>[:<group>]`.
Which command does the Docker example use?
The "USER - Set Runtime User" snippet uses `USER <username>[:<group>]`, from the Dockerfile section of the Docker cheat sheet.
What other Docker snippets are shown for "run as user"?
Besides "USER - Set Runtime User", this page also shows "Run as Non-Root User".
Is there anything to watch out for?
Yes. For "USER - Set Runtime User": All subsequent RUN, CMD, and ENTRYPOINT instructions run as this user. Running as root in production is a security risk - always create and switch to a non-root user for the final stage.