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
# Slow: any source edit re-runs npm ciFROM node:20-alpineWORKDIR /appCOPY . .RUN npm ciRUN npm run build # Fast: dependencies stay cached until the lockfile changesFROM node:20-alpineWORKDIR /appCOPY package.json package-lock.json ./RUN npm ciCOPY . .RUN npm run buildSee hits and misses
docker build --progress=plain .# #6 [3/6] RUN npm ci# #6 CACHED # Rebuild from scratch when debugging or refreshing apt packagesdocker build --no-cache .Cache mounts and CI cache
# syntax=docker/dockerfile:1# Package manager cache persists between builds but stays out of the imageRUN --mount=type=cache,target=/root/.npm npm ci --omit=dev# GitHub Actions: share cache across runs- uses: docker/build-push-action@v6 with: cache-from: type=gha cache-to: type=gha,mode=maxCommon MistakePutting
COPY . .before dependency installation. Every comment edit then reinstalls all packages.
Tip
RUN apt-get updatein its own layer can serve stale package lists from cache. Combine update and install in oneRUN.
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.