Lesson 47 showed you a multi-stage Dockerfile in one paragraph. This lesson builds one, line by line, and adds the tool that makes it fast. The first stage has the compiler and the build tools. The second stage has only the built app and the runtime. BuildKit adds cache mounts, so the dependency download survives from one build to the next. By the end your image is a tenth of the size it was, and the build is faster than the fat version.
Difficulty: Advanced · Know this first: Lesson 141 — Dockerfile Directives Part 1: Build the Image
Every hop charges rent in milliseconds. The bar below is a worked example for this lesson's scenario — not a measurement from a live system — but the shape is honest: on a cache hit the trip is almost free, on a miss the kitchen eats the budget. Step through the lesson or switch the scenario and watch the bar change.
Extra diagram · from scratch to master
Start with a fat image. Add one stage at a time until the same app ships in 120 MB.
The budget bar above shows three fixed stories. This simulator lets you write your own. Move a slider and watch the build, the pull, and the copy change in the budget bar, in the hop timings, and in the total. The numbers are a teaching example, not live measurements. The shape is the lesson: more stages and a colder cache mean a longer build, and a bigger final image means a longer pull.
How many stages the Dockerfile has. Each stage adds build work, and each stage that ships adds weight. Two stages is the usual shape: build, then run.
How big the final image is. A slim image is about 120 MB. A fat one is 1.4 GB. The pull time follows the size.
Share of the build the cache mounts cover. A warm cache means the downloads are reused. A cold cache means every build downloads again.
Try this: (1) Set stages to 5, final image to 1500, cache to 0. The build is about 60 min, the pull about 30 min, the copy about 5 min, and the total is about 97 min. (2) Set stages to 1, final image to 50, cache to 100. The build is about 2 min, the pull about 1 min, the copy about 1 min, and the total is about 6 min. Same app shape. Only the inputs changed.
Three questions. No score is saved anywhere — this is just you against the material.
Here is the multi-stage Dockerfile from this lesson, ready to edit. It builds in one stage and ships from a slim second stage, with a BuildKit cache mount on the install. Change it, then run the check.
Try breaking it on purpose: change AS build to AS builder, and leave the COPY --from=build line alone. Run the check and watch it fail. Then press Reset and try a change that keeps it passing, like adding a LABEL to the runtime stage.
COPY --from, flag by flag. A multi-stage build copies the built app out of the build stage and into the runtime stage. --from names the stage to copy from.
--from=build names the stage to copy from. Without it COPY reads from the build context, and the built files are not there, because they only exist inside the build stage.Flags you will meet next: --chown=node:node sets the owner on the copied files, and --chmod=755 sets their permissions.
Try it: change AS build to AS builder and leave the COPY --from=build line alone. The build fails at once, naming the stage that does not exist. That failure is the proof the flag reads the stage name, not the folder.
Expected output when it passes: The file has a build stage, a runtime stage, a copy from the build stage, a cache mount, and a non-root user. This image would build small and run safe.
I take the same image four times here. First I learn the two stages and what each one holds. Then I learn the copy that moves the app across. Then I learn the cache mounts that make the build fast. Last I measure the win, or it is a story.
Definition: A multi-stage build has more than one FROM line. The first stage is named build, and it holds the compiler and the build tools. The second stage is named runtime, and it starts from a slim base with no build tools. COPY --from moves the built files from the build stage into the runtime stage. The build stage is thrown away. The runtime stage is the image that ships.
Types:
Uses: I use this for every app with a build step. I write two stages, I copy the built files across, and I measure the size before and after. Try it now: change AS build to AS builder in the Try it box, leave the copy alone, and run the check to see the name mismatch fail. Then practice the split in the Docker labs.
Dimensions: At low traffic everything is nearly free. What breaks first is the name: a stage renamed in one place and not the other, or a copy path that does not exist in the build stage. It costs one careful read of the build error, which names the stage.
Try it: Basic
What ships at the end of a multi-stage build?
Now do it: On my lab machine with Docker, I change AS build to AS builder, leave the copy alone, and I run the check in the Try it box to see the name mismatch fail. Then I put the name back. Docker is not on this machine, so I run this on my lab machine.
Definition: COPY --from names the stage and the path, and both must be right. The stage name comes from the AS name on the FROM line. The path is the folder inside the build stage. A copy that names a stage that does not exist fails the build at once. A copy that names a path that does not exist fails the same way. A copy that takes too much makes the final image fat again, which defeats the whole point.
Types:
Uses: I use this to keep the final image slim. I copy the built output and the dependencies, and nothing else. I check the copy by building the build stage on its own with docker build --target build and listing the folder inside it. Try it now: add a third COPY --from line in the Try it box for a config file, and run the check. Then practice the copies in the Docker labs.
docker build --target, flag by flag. A multi-stage build has more than one FROM. --target stops the build at the stage I name, so I can look inside it.
--target build builds only up to the named stage and stops there. Without it the build runs every stage to the final one. I use it to open the build stage and look inside it before the runtime stage throws it away.-t names the image name:tag. Without it the image gets no name and no tag, and I cannot run it or push it by name.. the build context: the folder Docker may copy files from. It is a path, not a flag, and it is required. A stray 2 GB file in that folder gets sent to the daemon on every build.Flags you will meet next: --no-cache rebuilds every layer, and --platform builds for a different CPU.
Try it: build with --target build, then run that image and list /app. The build tools are there. Then build the full image and list /app again. The tools are gone. The target flag is how I proved it.
Dimensions: As the app grows, the copies grow, and a copy that takes too much is the fat image again. What breaks is the copy of the whole /app folder, tools and all. It costs a list of exactly what the runtime needs, written in the file.
Try it: Intermediate
What does COPY --from need to name correctly?
Now do it: On my lab machine with Docker, I run docker build --target build and I list /app inside it to check the copy path exists before I copy it. Docker is not on this machine, so I run this on my lab machine.
Definition: BuildKit is the modern build engine. Its cache mounts keep a folder across builds, so a download cache survives even when the layer cache misses. RUN --mount=type=cache,target=/root/.npm keeps the package cache between builds, and it adds no weight to the image, because a mount holds no files in the image. BuildKit also builds stages in parallel when they do not depend on each other, and it shows a better build log.
RUN --mount, flag by flag. A cache mount keeps the download cache across builds. It is the reason the second build is fast even when the layer cache misses.
--mount=type=cache,target=/root/.npm mounts a cache folder that survives between builds. type=cache says it is a cache. target says where it appears. Without it every build downloads the packages again. The mount adds no weight to the image, because a mount holds no files in the image.Flags you will meet next: type=bind mounts a file from the context, and type=secret mounts a secret that never lands in the image.
Try it: build twice with the mount and time both builds. The second one should be clearly faster. Then remove the mount and build twice again. The second build is slow again, because the cache is gone.
Types:
Uses: I use this when the build is slow even though the order is right. I add a cache mount to the install step, and I check the second build is faster than the first. Try it now: remove the --mount flag from the Try it box and run the check. The check fails, because the mount is part of this lesson file. Then put it back. Then practice the mounts in the Docker labs.
Dimensions: At ten times the builds, the mount cache is the difference between a two minute build and a twenty minute one. What breaks is the mount target: a path that does not match the tool cache folder, so the mount stays empty and the build stays slow. It costs one check of the tool docs for its cache folder.
Account for the size, stage by stage. A multi-stage build that is still big is big for a reason, and I find the reason by accounting for the size stage by stage. I list the layers of the final stage, add them up, and compare with the build stage. If the final stage is big, something from the build leaked in: a dependency, a cache, a tool. The accounting is a script over a layer list, and it names the leak instead of guessing at it.
Try it: account the stages in a sample layer list.
# python3 stage-sizes.py
stages = {"build": [("base", 120), ("tools", 650), ("deps", 300)], "runtime": [("slim base", 80), ("app", 15), ("deps", 25)]}
for stage, layers in stages.items():
total = sum(size for _, size in layers)
print(stage, "stage total (MB):", total)
print("saved by dropping the build stage (MB):", 1070 - 120)
Expected: build 1,070 MB, runtime 120 MB, saved 950 MB. If the runtime stage is over 200 MB, something from the build leaked into it.
Try it: Advanced
What does RUN --mount=type=cache do for my build?
Now do it: On my lab machine with Docker, I build twice with the mount and I time both builds. The second one should be clearly faster. Then I remove the mount and build twice again. Docker is not on this machine, so I run this on my lab machine.
Definition: At this level a slim image is not a one-off fix, it is the default: every Dockerfile has two stages, every install has a cache mount, every final image is measured, and the size is written down next to the build time. A deploy names the digest, so the same bytes run in staging and in prod. And I rehearse the worst day: the registry is slow, the pull is the deploy, and the small image is what saves it.
Types:
Uses: I use this when more than one team ships through the same pipeline. It is also how I review a setup I did not build: I ask for the image size, the stage count, and the pull time. If nobody knows the size, that is the first gap to close. Try it now: measure any image you own with docker images, and write the number down. If it is over 1 GB, that is the first gap to close.
Dimensions: At a hundred times the pulls, the image size is not the bottleneck, the blast radius is. What breaks is the single fat image every deploy depends on, or the registry that filled up with old layers. It costs a size budget, enforced in the pipeline, not a one-off cleanup.
Prove the cache mount is actually caching. A cache mount that is not mounted is a build that downloads everything every time, and the Dockerfile looks right while the build is slow. I prove it by building twice and comparing the times, then by checking the build log for the cache mount line. The second build should be fast. If it is not, the mount is missing, the cache key is wrong, or the build is not using BuildKit at all. The time is the test, not the Dockerfile.
Try it: run the two builds and compare the times.
# Two builds, same Dockerfile with a cache mount. Run on a host with Docker. # Dockerfile uses: RUN --mount=type=cache,target=/root/.npm npm ci export DOCKER_BUILDKIT=1 time docker build -t cache-test:1.0.0 . time docker build -t cache-test:1.0.0 . echo "Second build should be clearly faster. If it is not, the cache mount is not working."
export DOCKER_BUILDKIT=1, line by line. BuildKit is the modern build engine. This line turns it on for the shell I am in.
export DOCKER_BUILDKIT=1 turns on BuildKit for this shell. Without it the build uses the classic builder, and RUN --mount fails, because cache mounts are a BuildKit feature. The export lasts for the shell session. A new terminal needs it again.Flags you will meet next: DOCKER_BUILDKIT=0 turns it off again, and docker buildx build is the BuildKit command with more options.
Try it: build with BuildKit on and time the second build, then open a new terminal without the export and build again. The cache mount does nothing in the second terminal, because the classic builder does not know what --mount means.
Expected: the second build is much faster than the first. If both take the same time, BuildKit is off or the mount is not in the Dockerfile.
Try it: Master
At the master level, what names the exact bytes that ship?
Now do it: On my lab machine with Docker, I run docker images, I write down the size of one image I own, and if it is over 1 GB, that is the first gap I close. Docker is not on this machine, so I run this on my lab machine.
Start with the full file below. It is the multi-stage Dockerfile this lesson builds. Do this: save it as Dockerfile, run DOCKER_BUILDKIT=1 docker build -t app:1.0.0 ., and watch each stage. Expected output: the log shows the build stage running, then the runtime stage, and the last line names the image app:1.0.0.
FROM node:20 AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
COPY . .
RUN npm run build
FROM node:20-slim AS runtime
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
USER node
EXPOSE 3000
CMD ["node", "dist/server.js"]
npm ci --omit=dev, flag by flag. This line lives inside the Dockerfile. It installs exactly what the lock file says, and nothing extra.
npm ci installs exactly what the lock file says, and deletes node_modules first. Without the lock file it fails. That is the point: the build is reproducible, not close enough.--omit=dev skips devDependencies. Without it the image carries the test tools into prod, and the image is bigger for no reason.npm run build runs the build script from package.json. The script is the part that turns source into the files the server actually serves.Flags you will meet next: --omit=optional skips optional dependencies too.
Try it: build the image, then list /app/node_modules inside it. The dev tools should not be there. If they are, --omit=dev did not run, and the image is carrying test tools into prod.
What the snippet means: the build stage has the full Node image, the dependencies install with a cache mount, the code is copied, and the app is built. The runtime stage starts from a slim base, copies only the built output and the dependencies across, runs as a non-root user, declares its port, and starts the server. The build stage is thrown away.
Build one stage on its own to see what it holds. Do this: run docker build --target build -t app:build . and then docker run --rm app:build ls /app. Expected output: the listing shows the source, the built output, and the tools. Then run docker run --rm app:1.0.0 ls /app. Expected output: the listing shows only dist and node_modules. That is the split, proved by listing both images.
docker run --rm, flag by flag. A test container is a container I do not want to keep. --rm is the flag that makes it go away on its own.
--rm removes the container when it stops. Without it the stopped container stays listed and keeps its name, so the next run with the same name fails with a name conflict.--entrypoint echo replaces the image default entrypoint for this one run. The words after the image name become the arguments to the new entrypoint. Without it the image entrypoint runs, and the same words become its arguments instead. That is how one image answers two different questions.Flags you will meet next: -it gives you a terminal inside the container, and -e sets an environment variable.
Try it: run the same image twice with --rm, once with an extra argument and once without. Both runs print and vanish. Then run it once without --rm and run docker ps -a. The stopped container is still there, holding its name.
Prove the cache mount works with two builds. Do this: build once, note the time, change one line of code, and build again. Expected output: the second build is fast, and the log shows the install step reusing the mount even though the code layer rebuilt. Then remove the --mount flag, rebuild twice, and compare. Expected output: the second build without the mount is slower, because it downloads the dependencies again. Practice the split and the mounts in the Docker labs.
At 10x the images, the shape holds and the numbers grow. At 100x, the design changes: the base images are shared, the stage count is reviewed, and the image size is a budget enforced in the pipeline. The two stages never change. The discipline around them does. Lesson 146 is where the image gets safe to run in production.
Image size is a proxy. Pull time is the real cost, and it is what the deploy waits for. I measure it by removing the image and pulling it again, timing the pull. Then I do the same for the slim image. The gap in seconds is the deploy time I save on every rollout, on every host. A size saving that does not change the pull time is a saving that does not matter, and I find that out by timing it, not by reading the size.
# Time the pull of the big image and the slim image. Run on a host with Docker. docker rmi app:one app:two 2>/dev/null time docker pull app:one 2>/dev/null || echo "pull app:one from your registry to time it" time docker pull app:two 2>/dev/null || echo "pull app:two from your registry to time it"
docker pull, flag by flag. Pull downloads the image from the registry. It is the mirror of push, and the first step of every fresh deploy.
docker pull downloads the image from the registry. Without it run has to pull first, and a pull failure looks like a run failure.Flags you will meet next: docker pull --platform linux/amd64 pulls the image for one CPU type when the host could take another.
Try it: pull an image, then run docker images and check the size. Pull it again and watch it say up to date. The second pull moves nothing, because the layers are already on disk.
docker rmi, flag by flag. rmi removes images from the host. It is the cleanup command, and it refuses to remove an image a container still uses.
docker rmi removes an image from the host. It takes one or more names. An image that a container still uses cannot be removed until the container is gone.Flags you will meet next: docker rmi -f forces the removal, and docker image prune removes all unused images at once.
Try it: build two tags of one image, remove one with docker rmi, and list the images. The other tag is still there, because a tag is a pointer and removing one pointer does not delete the image.
Expected: the slim image pulls in a fraction of the time. If the times are close, the registry or the network is the bottleneck, not the image, and I fix that first.
Practice this in Lab 158 — Lesson 158 — Docker Lab: Small Images, Production Limits: the two-stage image in that lab drops from 1.4 GB to about 120 MB, with a BuildKit cache mount making the second build fast.
A deploy took ten minutes, and every host pulled a 1.4 GB image for an 80 MB app. The team blamed the network, then the registry, then the hosts. The network was fine. The image held the compiler, the build tools, and three versions of the dependencies, because the Dockerfile had one stage and the runtime copied the whole build folder across. The pull was the deploy, and the pull was slow because the image was fat.
Two things. First, every Dockerfile has two stages by default, and a single-stage Dockerfile needs a reason written in a comment. Second, I measure the image size on every deploy, and a deploy over 500 MB gets a question before it ships. Try it now: measure any image you own with docker images. If it is over 1 GB, split it before the next deploy.
Build a working two-stage image for the hello-docker app that ships at 120 MB or less, with a BuildKit cache mount on the install. It passes when the image builds, the app answers hello, the size is at most a tenth of the single-stage version, and the second build is faster than the first.
Success looks like this: the single-stage image is about 1.4 GB. The two-stage image is about 120 MB. Curl prints hello from the slim image. The second build is faster than the first. If the slim image is still over 500 MB, the runtime stage copied too much or starts from a fat base.
If the build fails naming a stage, the COPY --from name does not match the AS name. If the image is still fat, list its contents and find the weight. It is usually the build tools, copied by mistake. If the second build is as slow as the first, BuildKit is off or the mount target is wrong.