Dockerfile ends with root as the selected user

After completing build steps that require root, set a non-root default user for the application.

Description

A final USER root makes root the application’s default account. The deployment can override that choice.

Potential impact

A compromised process running as root can reach more files and processes inside the container. Its access to the host depends on capabilities, mounts and runtime isolation.

Remediation

Finish package installation and other privileged build steps first. Select a non-root account in the final stage, grant it access to the paths it needs, then test the application with the deployment’s user settings.

Examples

The excerpts omit the application files and startup command.

Before

dockerfile
FROM alpine:3.22
USER root
RUN adduser -D appuser

adduser creates appuser while the current user remains root.

After

dockerfile
FROM alpine:3.22
USER root
RUN adduser -D appuser
USER appuser

The final USER appuser switches the runtime default.

References