C.W.K.
Stream
Lesson 03 of 06 · published

Layer Caching — Order Matters

~16 min · dockerfile, performance

Level 0Container Curious
0 XP0/36 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Each instruction is a layer; each layer is cached

Docker checks each instruction against the cache. If the instruction and its inputs (files referenced by COPY, args used in RUN) haven't changed, the cached layer is reused. The first instruction whose cache misses busts every later layer.

The cache-busting bug

If you COPY . . before RUN pip install, then any code change re-copies everything, busts the install layer, and reinstalls every dependency. Slow. Annoying. Easily avoidable.

The fix: dependencies before code

Copy the dependency manifest (requirements.txt, package.json, Cargo.toml) first. Install. Then copy the rest of the source. Code changes don't bust the dependency layer.

Code

❌ BAD: any code change re-installs deps·dockerfile
FROM python:3.12-slim
WORKDIR /app

COPY . .                              # ← code AND requirements
RUN pip install -r requirements.txt    # ← reruns on every code edit

CMD ["python", "main.py"]
✅ GOOD: deps cached separately·dockerfile
FROM python:3.12-slim
WORKDIR /app

COPY requirements.txt .                # ← only the manifest
RUN pip install --no-cache-dir -r requirements.txt

COPY . .                              # ← code copied AFTER deps install

CMD ["python", "main.py"]

# Now: editing main.py rebuilds only the COPY . . layer.
# pip install layer stays cached until requirements.txt changes.
Same idea for Node·dockerfile
FROM node:22-alpine
WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build

CMD ["node", "dist/server.js"]

External links

Exercise

Take a Dockerfile from a real project. Time docker build with caching cold (use --no-cache). Make a one-line code change. Time docker build again. Then move the dependency-manifest copy ABOVE the source copy. Repeat both timings. Report the four numbers.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.