Layer Order and Dependencies
You'll learn why the order of layers in a container image matters and how each layer builds on the filesystem state left by the previous one.
The Stacking Rule
Container image layers aren't independent pieces—they're sequential building blocks. Each layer applies changes on top of the complete filesystem state created by all previous layers. Think of it like painting a wall: the second coat depends on the first coat being fully dry and in place. You can't apply the third coat before the second.
When a container runtime assembles an image, it processes layers in strict order from bottom to top. Layer 1 might create /app. Layer 2 can then add /app/config.json because /app exists. If you reversed the order, Layer 2 would fail—there's no /app directory to write into yet.
Dependencies Create Order
This sequential dependency means:
- Base layers establish foundations – system libraries, shells, package managers
- Middle layers add dependencies – language runtimes, frameworks
- Top layers add application code – your specific binaries and files
Each layer sees exactly what the union filesystem shows after all previous layers have been applied. If Layer 3 deletes a file created in Layer 2, Layer 4 won't see that file—even though it's still stored in Layer 2's data. The union filesystem hides it.
Why Order Matters for Caching
Because layers are ordered and immutable, changing Layer 2 invalidates all layers after it. Docker must rebuild Layer 3, 4, 5... even if their instructions haven't changed. This is why you put rarely-changing dependencies (base OS, frameworks) in early layers and frequently-changing code (your app) in later layers.
Key Takeaway: Layers form a strict dependency chain from bottom to top—each layer modifies the filesystem state inherited from all layers below it, making order critical for both functionality and cache efficiency.