How does Docker Layer Caching work and how do you order Dockerfile instructions for fast builds?
❓ Interview Prompt: Explain Docker build cache invalidation rules, layer ordering strategy, and how to maximize cache hit rates in CI/CD.
Docker builds images layer by layer. Each instruction creates an immutable layer identified by a hash of its inputs. If a layer's inputs haven't changed, Docker reuses the cached layer instead of re-executing the instruction — this is the build cache.
Cache Invalidation Rule:
Once any layer's cache is invalidated, all subsequent layers are also invalidated and rebuilt from scratch.
Optimal Ordering Strategy (Least → Most Frequently Changed):
FROM)RUN apt-get install)COPY package.json)RUN npm ci) ← CACHE HIT most of the timeCOPY . .) ← changes every commitRUN npm run build)Why This Matters:
If you put COPY . . before RUN npm ci, every single source file change invalidates the npm install layer — rebuilding node_modules on every commit wastes 2–5 minutes.
Code Implementation Example
# ✅ CORRECT ORDER — maximizes cache hits
FROM node:20-alpine
WORKDIR /app
# Step 1: Copy ONLY dependency manifests (changes rarely)
COPY package.json package-lock.json ./
# Step 2: Install deps — cached unless package.json changes
RUN npm ci
# Step 3: Copy source (changes on every commit — cache miss here is expected)
COPY . .
# Step 4: Build — also invalidated when source changes
RUN npm run build
# ❌ WRONG ORDER — npm ci re-runs on EVERY source change
# COPY . .
# RUN npm ci ← always a cache miss = wasted minutesPlace stable instructions (base image, system deps, package manifests) before volatile ones (source code). Cache invalidation is contagious — one miss rebuilds everything below.