Skip to content
BytePatterns

Images, Layers & Multi-Stage Builds

Docker & Kubernetes for Interviews: lesson 2 of 12

Order the Dockerfile by how often each line changes, and ship only the output.

Lesson 2 of 12 · 7 min

Images, Layers & Multi-Stage Builds

Step 1 of 11

Each Dockerfile instruction adds a layer: an immutable set of file changes, stacked in order.

The Idea

An image is a read-only template built from a Dockerfile, and each instruction adds a layer: an immutable set of file changes. Docker caches layers, but when one changes, it and every layer after it rebuild. So put what rarely changes — the base, the dependency install — first, and your source last.

Real-World Example

A Node API copies package.json and the lockfile, runs npm ci, then copies the source. A code-only edit reuses the cached dependency layer. A second FROM starts a slim runtime stage that copies in only the built output, leaving the toolchain behind.

The Tradeoff

Copy the whole repository before installing and every edit reinstalls every dependency. Name stages with AS so reordering the file does not break COPY --from. Pin the base image by digest when rebuilds must be identical.

Hands-On

# illustrative — cache-friendly order, two stages
FROM node:22 AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

FROM node:22-slim
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
CMD ["node", "dist/server.js"]

Your turn

Put the steps in the right order.

  1. COPY . . (the source code)
  2. FROM node:22 AS build
  3. RUN npm ci
  4. COPY package.json package-lock.json ./

Mini quiz

1 / 3

You edit one source file. With this lesson's Dockerfile, which steps rebuild?

Sources

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.