Sub topic 2
Why One Changed Step Rebuilds Everything After It
Assume you know docker build, docker run, and basic Dockerfile syntax. This chapter explains how cache invalidation affects build time and image size.
Cache invalidation cascades
Docker evaluates Dockerfile instructions in order. For each instruction, it checks whether the instruction and its inputs match a previously cached result. A matching result is a cache hit. Otherwise, Docker creates a new layer, which is a stored filesystem change.
When one step misses the cache, Docker normally rebuilds that step and every following step. Later instructions depend on the filesystem produced by earlier instructions, so Docker cannot safely reuse them.
Ordering instructions to keep the cache warm
Put stable inputs and expensive operations before frequently changing files. Copy dependency manifests first, install dependencies, and copy application source afterward.
FROM node:20-slim
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
CMD ["node", "dist/server.js"]Changing a source file invalidates COPY . . and the build step, but the dependency installation remains cached. Changing package-lock.json invalidates the install step and everything after it.
Why cleanup in a later layer fails
Each image layer preserves its own changes. If one layer downloads big.tar.gz and a later layer deletes it, the final filesystem hides the file, but the earlier layer still stores it.
Combine downloading, using, and deleting temporary files in one RUN instruction:
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl \
&& curl -fsSLO https://example.com/big.tar.gz \
&& tar -xzf big.tar.gz -C /opt \
&& rm -rf /var/lib/apt/lists/* big.tar.gzKeeping the build context small
The build context is the set of files sent to the builder. A .dockerignore file excludes files that the image does not need:
.git
node_modules
npm-debug.log
.env
distThis reduces upload time and prevents irrelevant changes from affecting COPY . ..
Exercise
If only src/app.js changes in the example Dockerfile, which steps should usually run again?
Show answer
COPY . . and RUN npm run build; the dependency installation should be a cache hit.