الانتقال إلى المحتوى
DevOps والـ CloudDocker· 7 دقائق للقراءة

Dockerfile Order Matters: Build Cache, Layers and Multi-Stage Builds

Docker reuses every step it can until one changes. Copy the lockfile before the source and builds stop reinstalling dependencies.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
محتويات المقال

A team's pull requests all wait on the same thing. Someone changes one line in a route handler, CI builds the Docker image, and the log shows RUN npm ci downloading every dependency again. On a laptop it's the same story: edit, rebuild, wait for packages that haven't changed. When someone suggests reordering the Dockerfile, the answer comes back quickly: it wouldn't help, because Docker rebuilds the whole image anyway.

The common misconception

The belief: the order of instructions in a Dockerfile doesn't affect build time, because every docker build starts from an empty image and runs every line. A Dockerfile reads like a shell script, and in a script the order decides whether it works, not how long the next run takes.

It's an honest conclusion from what people see. Both orders produce an image that works. And on many CI servers every build really does start cold: Docker's docs point out that in CI/CD pipelines "the builders are often ephemeral", which is why they recommend an external cache there. If your runner throws its cache away after each job, every build looks like a rebuild from scratch.

The half-truth: order doesn't change what the image does. It changes how much of the previous build Docker can reuse, and that's where the minutes go.

What actually happens

Every instruction is a cached step

Docker's cache docs say it plainly: "Each instruction in this Dockerfile translates to a layer in your final image." The article on images and layers showed that a is a read-only stack of those layers. The builder keeps the result of every step in its , and on the next build it goes through the Dockerfile in order, checking for each instruction whether it can reuse the stored result. When it can, the log says CACHED and the step costs almost nothing.

What counts as a change

The check depends on the instruction. For COPY and ADD, the builder "calculates a cache checksum from file metadata" of the copied files, and the cache is invalidated "if the file metadata has changed for any of the files involved." The modification time alone doesn't count: in our test, running touch on the source files left every step CACHED. For RUN, the builder doesn't look at what the command would download or produce; "just the command string itself is used to find a match."

One miss invalidates everything below it

This is the rule that makes order matter: "Once the cache is invalidated, all subsequent Dockerfile commands generate new images and the cache isn't used." Later steps re-run "even if they wouldn't build anything differently." So with COPY . . near the top, any change anywhere in the project misses the cache at that line, and the npm ci under it runs again. The docs' advice is to "order the instructions from less frequently changed to more frequently changed where possible."

Multi-stage builds separate building from running

A has several FROM instructions, and each one "begins a new stage of the build." You compile in one stage and copy only the output into the next, "leaving behind everything you don't want in the final image." The compiler, the type packages and the source files stay in the build stage. Each stage has its own steps in the cache, so the runtime stage's production install doesn't care when your source code changes.

The fix: dependencies first, source last

Here's a small Express API written in TypeScript, on node:24.22.2-alpine3.24:

Dockerfile Dockerfile
FROM node:24.22.2-alpine3.24WORKDIR /appCOPY . .RUN npm ciRUN npm run buildCMD ["node", "dist/server.js"]

We built each version in its own copy of the project on Docker Desktop (Engine 29.4.3, BuildKit 0.29.0), changed one line in src/server.ts, and built again. The output is trimmed to the steps that matter:

Bash terminal
docker build --progress=plain -t shop-api:wrong .# #7 [3/5] COPY . .# #7 DONE 0.2s# #8 [4/5] RUN npm ci# #8 DONE 44.1sdocker build --progress=plain -t shop-api:right .# #8 [build 4/6] RUN npm ci# #8 CACHED# #10 [build 6/6] RUN npm run build# #10 DONE 3.3s# #11 [stage-1 4/5] RUN npm ci --omit=dev# #11 CACHEDdocker image ls --format '{{.Tag}} {{.Size}}' shop-api# wrong 300MB# right 255MB

In the wrong version, the edited file changed the checksum of COPY . ., so the install under it ran again. Across our runs a full npm ci took between 3.8 and 44.1 seconds, depending on the network; on a real project it's whatever your full install costs. In the right version, COPY package.json package-lock.json ./ saw the same two files, so both installs came from the cache and only the TypeScript compile ran. The runtime image is also 45 MB smaller, because TypeScript and the type packages stayed behind in the build stage.

MythReality
Every build runs every instruction againEach step is reused from the cache until the first one that changed
Order only affects whether the image worksOrder decides how many steps run again after a change
Touching a file breaks the cacheCOPY compares a checksum of the files; a new modification time alone doesn't count
A cached RUN apk add curl fetches fresh packagesOnly the command text is compared, so the old result is reused
Build tools in the final image are harmlessA multi-stage build leaves them behind: 45 MB in our test

How to apply it in your project

  1. Find your first cache missChange one line of source code and build with --progress=plain. The first step that isn't CACHED shows where your order breaks, and every step under it pays again.
  2. Copy dependency files before the sourceCopy only the files your package manager reads, such as package.json and the lockfile, then install, then COPY . .. The install now re-runs only when dependencies change.
  3. Split build and runtime stagesCompile in a stage that has the SDK and dev dependencies, then start a second stage from a runtime image and copy in only the build output.
  4. Give CI a cache to reuseIf your runners are ephemeral, export the cache with --cache-to and read it back with --cache-from, as Docker's docs recommend for CI/CD. Otherwise every job starts cold, whatever your order.

Key takeaways

  • Docker reuses each Dockerfile step from its build cache until the first step that changed; every step after it runs again.
  • COPY misses the cache when the copied files change, not when only their timestamps do; RUN misses only when its text or an earlier step changes.
  • Put what changes least at the top: copy the lockfile, install, then copy the source.
  • A multi-stage build keeps compilers and dev dependencies out of the image you ship.
  • A cache hit can mean stale packages, so schedule rebuilds with --pull --no-cache.

📚 المصادر

  1. Docker build cache — Docker Docs
  2. Build cache invalidation — Docker Docs
  3. Optimize cache usage in builds — Docker Docs
  4. Multi-stage builds — Docker Docs
  5. Building best practices — Docker Docs

التعليقات (0)