An image is a stack of read-only diffs. Order them well and builds take seconds.
The mental model
An image is a stack of read-only layers. RUN, COPY and ADD each add a filesystem diff. Other instructions, like ENV, CMD and WORKDIR, only change metadata. A container adds one thin writable layer on top.
The build cache works top to bottom. Each step is reused if its instruction and inputs match a previous build:
- RUN is cached on the command text alone. Docker doesn't know that
apt-get updatewould fetch something new today. - COPY / ADD are cached on a checksum of the files being copied.
- Once one step misses the cache, every step after it rebuilds.
So put the steps that change rarely first, and the ones that change often last.
# syntax=docker/dockerfile:1 FROM node:20-slim AS build WORKDIR /app COPY package.json package-lock.json ./ RUN npm ci # cached until the lockfile changes COPY . . # source changes invalidate from here down RUN npm run build FROM node:20-slim WORKDIR /app ENV NODE_ENV=production COPY package.json package-lock.json ./ RUN npm ci --omit=dev COPY --from=build /app/dist ./dist USER node CMD ["node", "dist/server.js"]
Only the last stage ships. The build stage, with its dev dependencies and source code, is thrown away.
Commands
docker history --no-trunc myapp:1.4 # size added by each layer docker build --progress=plain . # see which steps show CACHED docker build --target build . # stop at a named stage docker build --no-cache . # force a full rebuild docker buildx du # build cache disk usage
Gotchas
- Deleting in a later layer doesn't shrink the image.
RUN rmwrites a whiteout; the bytes stay in the earlier layer. Download, use and clean up in the sameRUN, or use a multi-stage build. - Secrets persist too. A token copied in and then deleted is still in the layer.
ARGandENVvalues show up indocker history. UseRUN --mount=type=secret. - .dockerignore sits at the root of the build context. Exclude
.git,node_modules, logs,.envand build output. This shrinks the context, keeps secrets out of the image and stopsCOPY . .from missing the cache on unrelated changes. - Chain apt steps:
RUN apt-get update && apt-get install -y --no-install-recommends curl && rm -rf /var/lib/apt/lists/*. - Cache mounts (
RUN --mount=type=cache,target=/root/.npm npm ci) speed up reinstalls without adding the cache to the image.
Common wrong fix
When builds are slow or images are stale, many teams add --no-cache to CI for good. Every build then reinstalls every dependency, and image size doesn't improve at all. The real fix is instruction order: copy the lockfile, install, then copy the source. Pair that with a tight .dockerignore, and add --pull when you want a fresh base image.