Chapter 1 · Practice 3 of 5
Order instructions so dependency layers stay cached
Why it matters
Docker caches each instruction as a layer and reuses it until something that layer depends on changes. Once one layer is invalidated, every layer after it rebuilds too, so instruction order decides how fast your rebuilds are.
The rule: put what changes least at the top and your source code at the bottom. For dependencies, that means:
- Copy only the dependency manifest and lockfile.
- Install dependencies in their own
RUNstep. - Copy the rest of the code with
COPY . ..
A code change now skips the install step entirely. A RUN --mount=type=cache on the install step also keeps the package manager's download cache between builds.
Do
- Copy
package.jsonand the lockfile beforeCOPY . . - Install dependencies in their own
RUNstep - Use
RUN --mount=type=cachefor package manager caches
Avoid
COPY . .as the first instruction afterWORKDIR
Example
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .