✦ For everyone, free.

Practical knowledge for real and everyday life

Home

4.2.3.5 COPY Cache Strategy

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

A COPY cache strategy is the deliberate ordering and structuring of COPY instructions within a Dockerfile specifically to maximize how much of a typical rebuild can be served from Docker's layer cache, rather than letting instruction order be an afterthought.

The Core Principle: Stable Files First

Files that change infrequently should be copied, and any installation steps depending on them executed, before files that change frequently, so that frequent changes invalidate as little of the cache as possible.

COPY package*.json ./
RUN npm install
COPY . .

Because package*.json changes far less often than the rest of the application source, this ordering means npm install is reused from cache on the vast majority of rebuilds.

Splitting Broad Copies Into More Granular Ones

Rather than copying an entire project with a single COPY . ., splitting it into more granular copies based on which parts change at different rates can preserve caching more precisely.

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

If src/core/ changes far less often than src/ui/, this split allows the core build step to remain cached even when only UI code changes.

Avoiding Unnecessary Cache Invalidation From Unrelated Files

A broad COPY . . picks up every change in the build context, including files unrelated to a given build step, which can be avoided by either using a .dockerignore file or more narrowly scoped COPY instructions.

*.md
docs/
tests/

Excluding files that never affect the actual build (such as documentation) through .dockerignore prevents unrelated changes from invalidating cache layers that depend on the build context.

Measuring the Effect of a Cache Strategy

Comparing build times before and after restructuring COPY instructions for better caching is a direct way to confirm the strategy is actually working as intended.

time docker build -t myapp .
Why a Deliberate COPY Cache Strategy Matters

A thoughtfully structured sequence of COPY instructions, informed by how frequently different parts of a project actually change, can produce a substantial, compounding improvement in everyday build speed across a project's entire development lifecycle.