✦ For everyone, free.

Practical knowledge for real and everyday life

Home

4.3.1.1 Stable Instruction Order

A focused guide to Stable Instruction Order, connecting core concepts with practical Docker and container operations.

Stable instruction order is the practice of keeping a Dockerfile's instruction sequence consistent and predictable over time, specifically to preserve the build cache's effectiveness, since even harmless-looking reordering can unexpectedly invalidate cached layers that would otherwise have been reused.

Why Reordering Can Break Caching Unexpectedly

Docker's cache considers each instruction's position relative to what comes before it; reordering two instructions, even ones that seem logically independent, changes what state each instruction is evaluated against, potentially invalidating layers that would otherwise have remained cached.

COPY config.yaml .
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY config.yaml .

Even though both versions eventually copy the same two files, reordering them changes which layer a change to config.yaml would invalidate — in the first version, it invalidates the dependency installation step; in the second, it does not.

Keeping Related Changes Together

When refactoring a Dockerfile, intentionally preserving the relative order of instructions that affect caching, even while making other changes, helps avoid unintentionally degrading cache performance as a side effect of an otherwise unrelated cleanup.

git diff Dockerfile

Reviewing a diff of Dockerfile changes with cache implications specifically in mind, rather than only checking for correctness, helps catch unintentional reordering before it affects build performance.

Documenting Why a Particular Order Was Chosen

A brief comment explaining why instructions appear in a particular sequence — especially when the reasoning is specifically about cache behavior rather than logical necessity — helps prevent a future, well-intentioned reordering from undoing a deliberate optimization.

# Keep dependency installation before application source copy
# to preserve build cache across source-only changes.
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
Why Stable Instruction Order Matters

Treating a Dockerfile's instruction order as a deliberate, cache-relevant design decision — not just an arbitrary sequence that happens to produce a correct result — helps preserve build performance gains over the file's ongoing maintenance and evolution.