How to Write a Multi-Stage Dockerfile That Shrinks Images

If your production container ships a compiler, a package manager cache, and three copies of node_modules, your images are doing more work than they should. A multi-stage Dockerfile fixes that without much extra complexity: you build your app in one stage, then copy only the finished artifact into a small final image.

This guide walks through why Docker images bloat, what multi-stage builds change, and a full before-and-after example with Node.js. After that: the builder pattern, slim base images like distroless, layer caching tricks, a proper .dockerignore, and how to measure the result with docker images and docker history.

Why Docker images get bloated

Most bloated images start from a reasonable Dockerfile. You pick a full base image like node:20, install build tools, run npm install, copy the source, and build. Each step adds layers, and nothing removes them. The compiler you needed for one native dependency stays in the final image forever.

The usual culprits:

  • Build-only tools (gcc, make, python3) left behind in the final layer
  • devDependencies that never get pruned before the image ships
  • Package manager caches and source archives
  • A full OS base image when the app needs almost nothing at runtime
  • Accidentally copied files: .git history, local .env files, test fixtures

The result is an image that pulls slowly, eats registry storage, and carries a bigger attack surface than it needs.

What a multi-stage Dockerfile actually does

A multi-stage Dockerfile defines more than one FROM instruction. Each FROM starts a new stage with its own base image. You name stages with AS, run the heavy build work in the early stages, then COPY only the finished output into the final stage. The final stage decides the size and contents of your image; everything from earlier stages is left behind unless you copy it over.

Think of it as a workshop and a shipping box. The workshop has every tool you own. The shipping box carries only the finished product.

Before and after: a Node.js example

Here is the single-stage version most projects start with:

FROM node:20
WORKDIR /app
COPY . .
RUN npm install && npm run build
EXPOSE 3000
CMD ["node", "dist/server.js"]

It works, but the final image keeps node_modules, the npm cache, the raw source, and any build tools in one blob.

Now the same app as a multi-stage Docker build:

# Stage 1: build
FROM node:20 AS builder
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

# Stage 2: run
FROM node:20-slim
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./
EXPOSE 3000
CMD ["node", "dist/server.js"]

Only dist, the pruned modules, and package.json make it into the final image. The build cache, the unneeded source, and the dev dependencies stay behind in the builder stage, where nobody pulls them.

The builder pattern, step by step

Every multi-stage Dockerfile follows the same shape:

  1. Name the build stage. FROM node:20 AS builder marks the stage you will copy from later.
  2. Install from a lockfile. npm ci or go mod download keeps builds repeatable.
  3. Compile or bundle. Run tsc, go build, or cargo build --release here.
  4. Prune dev-only artifacts. Drop devDependencies and intermediate files.
  5. Copy the artifact. In the final stage, COPY --from=builder only what the runtime needs.

Each step stays small on purpose. Stages make the pipeline visible: anyone reading the file can see what gets built and what actually ships.

Slim finals: distroless, slim, or scratch

The final base image sets the floor for size and for the attack surface.

  • node:20-slim: the same runtime with Debian extras trimmed. Easy swap, and a shell still exists for debugging.
  • A distroless Docker image (for example distroless/nodejs): the runtime plus your app, no shell, no package manager. Smaller and harder to tamper with, though debugging usually means rebuilding with a debug variant.
  • scratch: literally nothing. This works for statically linked binaries, like a Go binary built with CGO_ENABLED=0. No shell at all, so the app must be fully self-contained.

Move in that order as you get comfortable: slim first, distroless once the app is stable, scratch for static binaries. There is no single right answer, only trade-offs between debuggability and size.

Layer caching tips to keep builds fast

Small images should not come at the cost of slow builds. Dockerfile layer caching lets Docker reuse unchanged layers, and the order of your instructions decides what gets reused.

  • Copy dependency manifests first, install, then copy source. Code changes then only rebuild the top layers.
  • Put rarely changing instructions (base image, system packages) near the top.
  • Combine related RUN commands with && to keep the layer count low.
  • Use BuildKit cache mounts (--mount=type=cache) so package manager caches speed up builds without being shipped.

One thing to expect: COPY –from=builder invalidates the layers below it when the builder output changes. That is normal; the final image rebuild is usually the fast part of the build.

Keep junk out with .dockerignore

Everything COPY . . grabs, including .git, logs, and a local node_modules, lands in a layer. A .dockerignore works like .gitignore for the build context:

.git
node_modules
*.log
.env
dist
coverage

A smaller build context means faster builds and fewer accidental secrets baked into images. Treat .dockerignore as part of the Dockerfile, not an afterthought.

Measure your image size

Do not guess. After building, run:

docker images my-app
docker history my-app --no-trunc

docker images shows the final size. docker history lists every layer with its size and the command that created it, so you can spot the layer that blew the image up. Build the single-stage and multi-stage variants side by side and compare the numbers yourself. Your savings depend on your app, but the before-and-after usually settles the argument on its own.

Frequently asked questions

Do multi-stage builds make builds slower?

Slightly, on a cold cache, since there are more stages. With layer caching the rebuild cost is close to the single-stage version, and the pull and push savings at deploy time usually win.

Can I use multi-stage builds with any language?

Yes. The pattern stays the same: a build stage with the toolchain, a final stage with the runtime. Go binaries can even target scratch.

Should the final stage always be distroless?

Not always. Distroless is great for stable apps, but during active development a slim image with a shell is easier to debug. Pick based on the phase your app is in.

How many stages can a Dockerfile have?

As many as you need, but most real-world files use two or three: dependencies, build, and runtime. Extra stages only add readability if they earn it.

Start with one Dockerfile

Add a builder stage, copy the artifact into a slim final image, and add a .dockerignore. Run docker history before and after, and look at what disappeared from the layer list. Once the pattern clicks, distroless finals and cache mounts are natural next steps. Once your images are lean, the next question is where they run; our Docker Compose vs Kubernetes guide walks through that choice.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.