DEV Community

Darshan Vasani
Darshan Vasani Subscriber

Posted on • Edited on

🧩 Docker Layer Caching

🧩 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!
Enter fullscreen mode Exit fullscreen mode

βœ… 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
Enter fullscreen mode Exit fullscreen mode

🧠 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)