COPY order & build cache

Cache dependencies before copying source

Lesson 5 of 20 · 12 min · Module 2: Build an image contract

Arrange build inputs so a source edit does not invalidate unrelated dependency work.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Separate dependency inputs from source
  • Read the build as an ordered sequence

The idea

Image instructions are an ordered build contract. A later instruction can change a default established earlier; the final stage determines the output image.

01Separate dependency inputs from source

npm ci uses the lockfile and package manifest. Copy those first so a change to application source need not invalidate the installation layer.

02Read the build as an ordered sequence

Docker cache reuse depends on instructions and their inputs. Copying the whole context before installation ties that installation layer to every source edit.

03Verify the order rather than the spelling

The checks inspect the parsed COPY instructions and their positions relative to RUN. Comments containing command names do not satisfy the task.

Your turn

Use node:22-alpine and /app. Copy package.json and package-lock.json to ./, run npm ci, then copy src/ to ./src/. Start node src/server.js in exec form.

What the checks look for

  • Copies both dependency manifests
  • Installs between manifest and source copies
  • Starts the source entry point
Try it in the editor →

Take this with you

Order build layers around the inputs that actually change.

Go a little further

Explain how editing package-lock.json should affect the dependency layer.

Learn Docker & Containers for free

20 short lessons with real code and instant checks.

See the whole course →