Docker Best Practices

Chapter 1 · Practice 3 of 5

Order instructions so dependency layers stay cached

From Writing the Dockerfile

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:

  1. Copy only the dependency manifest and lockfile.
  2. Install dependencies in their own RUN step.
  3. 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.json and the lockfile before COPY . .
  • Install dependencies in their own RUN step
  • Use RUN --mount=type=cache for package manager caches

Avoid

  • COPY . . as the first instruction after WORKDIR

Example

Dockerfile
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci
COPY . .