Skip to content
Optimal Lab

DevOps · interactive

Docker images and layer caching

Each line of a Dockerfile builds a layer, and Docker reuses a layer only if nothing it depends on changed, including every layer above it. Change one file and see how much reruns, then reorder the file.

Dockerfile · Copy everything first

build: 67 s

  1. FROM node:22-slimCACHED
  2. WORKDIR /appCACHED
  3. COPY . .rebuild 2 s
  4. RUN npm cirebuild 45 s
  5. RUN npm run buildrebuild 20 s
  6. CMD ["node", "dist/server.js"]rebuild 0 s

“COPY . .” sees a change, so it and every layer after it rebuild: 67 s.

Dockerfile

COPY . . comes before npm ci, so any file change invalidates the install.

What changed since the last build?

  1. 1

  2. 2

  3. 3

    Once a layer rebuilds, every layer after it must too, even if its own instruction is unchanged.

    From line 3 down: 4 layers, 67 s.

  4. 4

In production

Tools and technologies

Layer caching works the same in every OCI image builder; order decides how much is reused.

Not tied to one language — use these names when you search docs or design a system.