Build cache

docker build reuses a layer when its instruction and its inputs have not changed since the last build. The first instruction that changes invalidates the cache of every instruction after it.

How it works

For RUN, the cache key is the text of the command; for COPY and ADD, it is the content of the copied files. That is why Dockerfiles copy the dependency manifest first, install the dependencies, and only then copy the source code, which changes with every commit.

What breaks

COPY . . before npm ci or pip install means a one-line code change reinstalls every dependency: builds go from seconds to minutes. Look for CACHED in the build output to see what was reused.

In a Dockerfile

FROM node:20-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
COPY src ./src
CMD ["node", "src/server.js"]

See it break, then fix it

Write the Dockerfile or the compose file, type the docker commands, and watch a simulated server run them through reboots, upgrades and traffic. Free to start.