Script Valley
Docker: Complete Course
Building Docker Images with DockerfileLesson 2.2

How Docker layer caching works and how to exploit it

layer cache invalidation, cache-busting, dependency layer trick, cache ordering, build performance, --no-cache flag

Layer Caching Is Your Biggest Build-Speed Lever

Docker layer cache invalidation diagram

Docker caches each layer. On rebuild, it reuses cached layers until it detects a change. Once any layer is invalidated, all subsequent layers must rebuild โ€” even if their content is identical.

The Dependency Layer Trick

This is the single most impactful Dockerfile optimization:

# BAD โ€” source changes invalidate the npm install layer
COPY . .
RUN npm ci

# GOOD โ€” npm install is cached unless package.json changes
COPY package*.json ./
RUN npm ci --omit=dev
COPY . .

By copying only the manifest first and running install before copying source, you get a cached install layer on every rebuild where only code (not dependencies) changed. A full project rebuild drops from 45 seconds to 3 seconds.

What Invalidates a Cache Layer

Any of these bust the cache for that layer and all layers below it: the instruction text changed, a COPY or ADD source file changed (Docker checksums files), or --no-cache was passed to docker build.

# Force a clean rebuild ignoring all cache
docker build --no-cache -t myapp .

Always order Dockerfile instructions from least-frequently-changing to most-frequently-changing: base image โ†’ system packages โ†’ dependency install โ†’ app source copy โ†’ startup command.

Up next

Multi-stage Docker builds for smaller production images

Sign in to track progress

How Docker layer caching works and how to exploit it โ€” Building Docker Images with Dockerfile โ€” Docker: Complete Course โ€” Script Valley โ€” Script Valley