Skip to main content

Build Cache

Docker build cache is the mechanism that reuses unchanged layers from earlier builds instead of re-running their instructions. A changed layer invalidates every layer after it, so Dockerfile order determines build speed.

How the build cache decides

For each instruction, Docker checks whether it has already built an identical layer from the same parent. For RUN, the cache key is the instruction text plus the parent layer. For COPY and ADD, it also includes a checksum of the copied files. A match means a cache hit and the step is skipped. A miss rebuilds that step and everything below it.

Order instructions from stable to volatile

Dockerfile
# Slow: any source edit re-runs npm ci
FROM node:20-alpine
WORKDIR /app
COPY . .
RUN npm ci
RUN npm run build
# Fast: dependencies stay cached until the lockfile changes
FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

See hits and misses

Bash
docker build --progress=plain .
# #6 [3/6] RUN npm ci
# #6 CACHED
# Rebuild from scratch when debugging or refreshing apt packages
docker build --no-cache .

Cache mounts and CI cache

Dockerfile
# syntax=docker/dockerfile:1
# Package manager cache persists between builds but stays out of the image
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
YAML
# GitHub Actions: share cache across runs
- uses: docker/build-push-action@v6
with:
cache-from: type=gha
cache-to: type=gha,mode=max
Common Mistake

Putting COPY . . before dependency installation. Every comment edit then reinstalls all packages.

Tip

RUN apt-get update in its own layer can serve stale package lists from cache. Combine update and install in one RUN.

Frequently Asked Questions

Why did one small change make my whole build slow?

Cache invalidation cascades downward. If a layer near the top changed, such as a broad COPY . ., every later layer rebuilds even if its own instruction is unchanged. Move volatile steps to the end.

How do I share build cache between CI runs?

CI runners are usually fresh machines, so use BuildKit's external cache with --cache-to and --cache-from, for example a registry cache or the GitHub Actions cache backend with mode=max to include intermediate layers.

When should I disable the cache?

Use --no-cache when you need fresh OS packages, suspect a stale layer, or want to prove the Dockerfile builds from scratch. Do not use it routinely, since it throws away the main speed benefit.

Found a mistake, an outdated step or a broken link?