Layer Caching Fundamentals
You'll learn how Docker reuses previously built layers to speed up image builds dramatically.
Why Caching Matters
Every RUN, COPY, ADD, WORKDIR, and most other Dockerfile instructions create a new layer. Docker is smart: before executing an instruction, it checks if it has already built an identical layer from a previous build. If the instruction and its context haven't changed, Docker reuses the cached layer instead of rebuilding it.
Think of it like cooking: if you've already chopped onions and stored them in the fridge, you don't chop them again for the next recipe—you just grab what you cached.
How Layer Order Affects Cache Hits
Docker evaluates caching from top to bottom. The moment one instruction invalidates the cache (because something changed), all subsequent layers must rebuild—even if they haven't changed.
Example scenario:
FROM node:18
COPY package.json .
RUN npm install
COPY . .
If you change application code but not package.json, only the final COPY . . rebuilds. The expensive npm install stays cached.
But if you wrote:
FROM node:18
COPY . .
RUN npm install
Every code change invalidates COPY . ., forcing npm install to re-run unnecessarily—even though dependencies didn't change.
The Golden Rule
Place frequently changing instructions near the bottom and stable, expensive operations near the top. This maximizes cache reuse across builds.
Key Takeaway: Docker caches layers sequentially; once a layer changes, all layers below it rebuild. Smart instruction ordering keeps slow operations cached while fast changes invalidate only the final layers.