Dockerfile: Avoid Using RUN with sudo

RUN with sudo is redundant in Dockerfiles and can hide privilege assumptions. Use USER correctly and execute package commands without sudo.

Problem

Using sudo inside Dockerfile RUN commands is usually redundant and hides privilege assumptions. Docker already controls execution user with the USER directive. Action: remove sudo and make privilege transitions explicit per build stage.

Description

sudo often fails in minimal images because the binary is missing. Adding it just for build steps increases complexity without improving security. Action: rely on stage design and USER transitions instead of shell escalation.

Reviewers need clear privilege boundaries to reason about risk. A command that includes sudo can look intentional while still running as root in practice. Action: keep privileged build steps grouped together, then switch to a non-root runtime user before the final stage.

Consistent USER usage also improves policy automation. Linters and admission checks can verify user context when privilege is declared in Dockerfile metadata, not embedded in shell commands. Action: standardize this pattern in templates and CI checks.

Use this rollout checklist to eliminate sudo safely:

  • Remove sudo from Dockerfile RUN commands.
  • Keep privileged setup in explicit root sections only.
  • Create and switch to a fixed non-root runtime user.
  • Add a CI assertion that runtime containers do not start as root unless approved.

Treat verification as part of the rule, not optional cleanup. Action: automate a static check, a build check, and a runtime smoke check in the default CI pipeline so regressions are caught before review.

  • Static check: fail when the disallowed pattern appears in Dockerfile or manifest.
  • Build check: run a minimal image build to confirm the secure pattern is valid.
  • Runtime check: start the workload and assert expected behavior with one deterministic probe.

Examples of code

Problematic code

FROM ubuntu:24.04
USER app
RUN sudo apt-get update && sudo apt-get install -y curl

Verified code

FROM ubuntu:24.04
USER root
RUN apt-get update && apt-get install -y --no-install-recommends curl
RUN useradd -m -u 10001 app
USER app

Related rules