Module #2 · beginner Article
Images, layers, and the Dockerfile instruction order that matters
How UnionFS stores image diffs and why ordering copy steps determines build cache efficiency.
14 min read+10 XPPublished 2026-07-01
Layer Immutability and Union Filesystems
Docker images are composed of stacked, read-only layers managed by an overlay filesystem (Overlay2). When a container starts, Docker adds a single thin read-write container layer on top.
The Invalidation Chain
Docker evaluates instructions top-to-bottom. If a layer's checksum matches the cache, Docker skips execution. But as soon as one instruction changes (e.g., source code modification), every layer defined after it is invalidated and rebuilt from scratch.
# BAD PATTERN: Copying code before installing dependencies
FROM node:20-alpine
WORKDIR /app
COPY . . <-- Invalidates cache on every single line of code changed!
RUN npm install <-- Re-runs slow dependency download every build!
# OPTIMIZED PATTERN: Separate dependency manifest from source code
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./ <-- Only invalidates when package.json actually changes
RUN npm ci --only=production
COPY . . <-- Source code changes only invalidate this final fast layer
Finished reading?
Mark as complete to claim your +10 XP and track progress.
