Dockerfile: Use WORKDIR Instead of ‘RUN cd …’

Using RUN cd in Dockerfiles is fragile and harder to read. Set WORKDIR once and run commands relative to that directory for predictable builds.

Problem

RUN cd changes directory for one shell command only and makes Dockerfiles fragile during refactors. Action: set WORKDIR once per stage and run commands relative to that persistent context.

Description

WORKDIR is explicit Docker metadata, while chained cd commands hide path assumptions inside shell expressions. Hidden assumptions break easily when command order changes. Action: replace cd chains with stage-level WORKDIR declarations.

Reordering, splitting, or merging RUN commands can silently change relative paths in cd-based builds. That increases review difficulty and troubleshooting time. Action: keep path context explicit and stable by defining directories once at the stage level.

Absolute WORKDIR paths also improve portability between base images and reduce inherited state surprises. In multi-stage builds, consistent directory boundaries simplify artifact transfer and debugging. Action: standardize absolute stage directories across services.

Use this rollout checklist to remove cd drift:

  • Replace RUN cd ... && ... patterns with explicit WORKDIR.
  • Use absolute stage paths such as /app or /workspace.
  • Keep COPY and entrypoint paths aligned with declared WORKDIR.
  • Block new RUN cd patterns with Dockerfile linting rules.

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
RUN cd /app && make build && make test

Verified code

FROM ubuntu:24.04
WORKDIR /app
RUN make build && make test

Related rules