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 explicitWORKDIR. - Use absolute stage paths such as
/appor/workspace. - Keep
COPYand entrypoint paths aligned with declaredWORKDIR. - Block new
RUN cdpatterns 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 testVerified code
FROM ubuntu:24.04
WORKDIR /app
RUN make build && make test