π§© Docker Layer Caching: What & Why?
When you build a Docker image, each instruction (like COPY
, RUN
, etc.) creates a layer. Docker caches these layers π so it can reuse them in future builds, making things faster!
π₯ Why Layer Order Matters
Docker reads your Dockerfile
top to bottom πβ¬οΈ
The first changed line invalidates the cache for all lines after it βπ«
π Example: Bad vs Good Sequence
π« BAD Dockerfile (Unoptimized Layer Order)
COPY . . # β Copies everything first (even changing README breaks cache)
RUN npm install # Cache busts often!
β GOOD Dockerfile (Optimized Layer Order)
COPY package*.json ./ # β
Only changes when dependencies change
RUN npm install # β
Reused most of the time
COPY . . # β
Source code comes after
π§ Why?
- If you copy the whole source before installing deps, any code change breaks the cache for dependencies!
- By copying just
package.json
first, Docker only re-installs when dependencies change.
β Recommended Layer Order Cheat Sheet π
Layer | Why It Comes Here |
---|---|
FROM |
Base image, foundation layer ποΈ |
WORKDIR |
Set working directory π |
COPY package*.json ./ |
Dependency file copied first for caching π§ |
RUN npm ci or RUN npm install
|
Install deps (caches as long as package.json doesnβt change) π¦ |
COPY . . |
Now copy the actual app code π§βπ» |
EXPOSE & ENV
|
Doesnβt affect cache much, but goes here π |
CMD |
Entrypoint, doesn't affect caching π’ |
π§ Pro Caching Tips
π‘ Tip | π οΈ Description |
---|---|
π§© Use .dockerignore
|
Prevent unnecessary files (e.g. .git , node_modules ) from breaking cache. |
π§ͺ Use npm ci
|
Faster and more reproducible in CI/CD than npm install . |
π§βπ Split dev & prod builds | Use multi-stage builds to keep production images small and cache efficient. |
π Use exact base versions | Use node:20-alpine instead of node:alpine to avoid unexpected cache busts. |
π Visual Analogy
Think of Docker caching like making layered sandwiches π₯ͺ:
- π₯ If you change the base bread (early layers), the whole sandwich needs to be rebuilt.
- π§ But if you change just the top slice of tomato π (code), you donβt need to rebuild the whole thing.
π Final Thought
π¬ Always structure your Dockerfile to keep slow-changing layers at the top and fast-changing layers (like source code) at the bottom β this will save build time β±οΈ and make CI/CD faster β‘.
Top comments (0)