✦ For everyone, free.

Practical knowledge for real and everyday life

Home

4.3.1.3 Cache Invalidation Control

A focused guide to Cache Invalidation Control, connecting core concepts with practical Docker and container operations.

Cache invalidation control is the deliberate practice of structuring a Dockerfile so that the developer, rather than incidental file changes, determines precisely which layers get invalidated and rebuilt on a given change, by carefully isolating what each instruction actually depends on.

Isolating What Triggers Invalidation

A layer's cache is invalidated based on the exact content it depends on — for COPY, the files being copied; for RUN, the literal instruction text. Structuring a Dockerfile so each layer depends on the narrowest possible set of inputs gives precise control over what triggers a rebuild.

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

Here, only a change to requirements.txt invalidates the dependency installation layer; a change to any other file does not.

Splitting Broad Copies Into Narrower Ones for Finer Control

Rather than a single broad COPY . ., splitting copies by directory or purpose allows more precise control over which specific changes invalidate which specific layers.

COPY src/core/ ./src/core/
RUN ./build-core.sh
COPY src/plugins/ ./src/plugins/
RUN ./build-plugins.sh

A change limited to src/plugins/ invalidates only the plugin build step, leaving the core build step's cache intact.

Using .dockerignore to Prevent Unintended Invalidation

Excluding files that have no actual bearing on the build, but would otherwise be picked up by a broad COPY, prevents irrelevant changes from triggering unnecessary cache invalidation.

*.md
docs/
.github/
Forcing Invalidation Deliberately When Needed

Sometimes a rebuild needs to be forced even though nothing the cache considers has changed — for example, to pick up an upstream package update — which can be done explicitly rather than relying on accidental invalidation.

docker build --no-cache -t myapp .
Why Deliberate Cache Invalidation Control Matters

Treating cache invalidation as something to actively design for, rather than an incidental side effect of however a Dockerfile happens to be written, produces builds that are both fast in the common case and correctly, predictably invalidated exactly when something relevant actually changes.