Docker & Containers (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
How does Docker build layer caching work, and how should instructions be ordered to maximize cache hits?
senior LevelMost AskedCode ExampleDocker & ContainersSystem Design
In Simple Words: Docker executes Dockerfile instructions from top to bottom. Each instruction generates a layer cached by cryptographic hash.
- For
RUN, Docker checks if the command string matches a cached layer. - For
COPYandADD, Docker computes checksums of local files. If even one byte changed, the cache for that step and every subsequent step is completely invalidated.
Ordering Rule: Order from least-frequently changed to most-frequently changed
dockerfile
# ❌ ANTI-PATTERN: Invalidates cache on EVERY code edit
FROM node:20-alpine
WORKDIR /app
COPY . . # Busts cache every time you change a line of code!
RUN npm install # Re-downloads 500MB of packages on every build!
CMD ["node", "index.js"]
# ✅ OPTIMIZED PATTERN:
FROM node:20-alpine
WORKDIR /app
# 1. Copy package files first
COPY package*.json ./
# 2. Install dependencies (cached until package.json changes!)
RUN npm ci --only=production
# 3. Copy source code last (changes frequently, but npm ci remains cached)
COPY src/ ./src/
CMD ["node", "src/index.js"]