FALVARIX
FALVARIX
devops --real --no-hype

Docker multi-stage builds: 80% smaller images

Docker multi-stage builds: 80% smaller images

Docker multi-stage builds: 80% smaller images

There’s an awkward moment in the life of every team that runs containers: someone runs docker images on the production server and discovers that the “four endpoints” API weighs 1.2 GB. Inside that image travel the compiler, the package manager, the development headers, the dependency cache and, if you’re unlucky, a forgotten .env buried in an intermediate layer.

A fat image isn’t just a matter of aesthetics. It means slower deployments, higher registry storage costs, painful cold starts on Kubernetes and, above all, a huge attack surface. Docker multi-stage builds are the most cost-effective technique for fixing this: with very little effort you can shave off between 70% and 95% of the size, and along the way close doors that should never have been open.

Why your images are so heavy (and why it matters in production)

The root of the problem is almost always the same: using the same image to build and to run. Compiling an application requires heavy tools (gcc, npm, maven, pip plus their build-essential). Running it, on the other hand, only needs the binary or final artifacts and a minimal runtime.

When both phases share an image, everything needed to build ends up in production. The consequences are concrete:

  • Slow deployments: every node has to download hundreds of unnecessary megabytes, and during autoscaling that shows up in critical seconds.
  • More vulnerabilities: every extra package is a candidate for a CVE. A scanner run against a full node:20 image typically reports hundreds of findings, most of them in packages your application never touches.
  • Tools for the attacker: if someone gets command execution inside the container, finding curl, wget, a shell and a package manager saves them a lot of work.
  • Compounding costs: registries, cross-region transfer and pipeline time multiply with every published version.

What a multi-stage build is and how it works

A multi-stage build lets you define several FROM stages in a single Dockerfile. Each stage starts from its own base image and can copy files from earlier stages with COPY --from. Only the last stage defines the final image; everything else is discarded.

In other words: you cook in a fully equipped kitchen and serve the dish on a clean tray, without dragging the stove into the dining room.

Practical Go example: from ~900 MB to ~15 MB

Go is the textbook case because it produces static binaries:

# Etapa 1: compilación
FROM golang:1.22 AS builder
WORKDIR /src
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o /app ./cmd/api

# Etapa 2: ejecución
FROM gcr.io/distroless/static-debian12:nonroot
COPY --from=builder /app /app
USER nonroot:nonroot
ENTRYPOINT ["/app"]

The golang image comes in around 800-900 MB; the final result lands in the 10-20 MB range, with no shell, no package manager and running as a non-privileged user. That’s over a 98% reduction.

Node.js example: separating build and runtime dependencies

In interpreted languages the reduction is smaller, but still very significant:

FROM node:20-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci

FROM deps AS build
COPY . .
RUN npm run build && npm prune --omit=dev

FROM node:20-alpine AS runtime
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build /app/dist ./dist
COPY --from=build /app/node_modules ./node_modules
COPY package.json ./
USER node
CMD ["node", "dist/server.js"]

The trick here comes down to three decisions: use an Alpine base, purge the devDependencies with npm prune --omit=dev, and don’t copy the source code or the npm cache into the final image. Going from a standard node:20 with everything included (close to 1.1 GB) to around 150-200 MB works out to an 80-85% cut.

Choosing the final base image: alpine, slim, distroless or scratch

The runtime stage is where you win or lose the game. These are the usual options:

BaseApproximate sizeShellWhen to use it
scratch0 MBNoStatic binaries (Go, Rust with musl)
distroless2-30 MBNoGo, Java, Python, Node when you don’t need a shell
alpine~5 MBYes (busybox)When you need to debug or install something specific
-slim (Debian)30-80 MBYesglibc compatibility without the headaches

One important caveat about Alpine: it uses musl instead of glibc, which can cause odd behavior with certain native Python or Node libraries. If you compile binary dependencies and start seeing strange failures, a -slim base is usually the saner choice rather than fighting musl.

Distroless images, maintained by Google, strip out the shell and package manager. Debugging gets harder, but that’s precisely the point: what doesn’t exist can’t be exploited. For one-off diagnostics, you can use ephemeral debug containers in Kubernetes instead of leaving tools permanently in the image.

Security: what you gain beyond size

Shrinking megabytes is the visible benefit; the security improvement is the real value. With multi-stage builds you get several things at once.

Smaller attack surface

Fewer packages means fewer CVEs to patch and less noise in your scanner reports. Tools like Trivy, Grype or Docker Scout itself let you measure it: run the scan before and after and compare. It’s a great metric for justifying the work to your team.

Running without privileges

Always add USER with a non-root user in the final stage. By default, processes in containers run as root, and combined with a misconfigured set of capabilities that can make an escape easier. Round it out with readOnlyRootFilesystem: true and allowPrivilegeEscalation: false in your Kubernetes securityContext.

Secrets that don’t linger in layers

Here’s a classic trap: passing a token as ARG or copying an SSH key to clone a private repo leaves a trace in the layer history, even if you delete it afterward. With multi-stage the risk is lower because the build stage isn’t published, but the right approach is to use BuildKit secrets:

RUN --mount=type=secret,id=npm_token \
    NPM_TOKEN=$(cat /run/secrets/npm_token) npm ci

The secret is mounted only for that RUN and is never written to a layer. And for runtime secrets, avoid variables baked into the image; in secret management with OpenBao we explain how to get them out of your code and out of Git entirely.

Pinned versions and reproducibility

Avoid latest. Pin the base image version and ideally its digest (FROM node:20-alpine@sha256:...). That way you guarantee that what passed the security scan is exactly what gets deployed.

Best practices that multiply the effect

Multi-stage is the foundation, but there are habits that lock in the result.

  1. Order layers by frequency of change. Copy dependency files first (package.json, go.mod, requirements.txt) and then the code. That way Docker’s cache keeps you from reinstalling everything on every commit.
  2. Use a strict .dockerignore. Exclude .git, node_modules, *.md, test directories and any .env. It shrinks the build context and prevents accidental leaks.
  3. Combine RUN commands wisely. Installing and cleaning up in the same layer (apt-get install ... && rm -rf /var/lib/apt/lists/*) keeps the junk from landing in an earlier layer.
  4. Enable BuildKit and remote cache. With docker buildx you can export the cache to your registry, which dramatically speeds up pipelines on ephemeral runners.
  5. Add a HEALTHCHECK or Kubernetes probes so the orchestrator can detect zombie containers.

You can also use stages as targets: docker build --target test . runs a test stage inside the same Dockerfile, so tests and production share exactly the same dependencies.

Wiring it into your CI/CD pipeline

Optimizing the Dockerfile is of little use if nobody verifies it stays that way. The recommended flow is:

  1. Build with BuildKit and remote cache.
  2. Scan the image with Trivy or Docker Scout and fail the pipeline on critical vulnerabilities with an available patch.
  3. Sign the image (with Cosign, for example) and generate an SBOM.
  4. Publish to the registry only if everything above passes.

If you use GitHub, the docker/build-push-action action integrates BuildKit cache and secrets with minimal configuration; in our guide to CI/CD with GitHub Actions and frictionless pipelines you’ll find the full structure to slot it in. And once the image is published, declarative deployment with GitOps, ArgoCD and Kubernetes gives you traceability and instant rollbacks if a new version misbehaves.

Common mistakes when adopting multi-stage builds

  • Copying too much from the builder. A blanket COPY --from=builder /app . drags along source code and intermediate artifacts. Copy only what’s strictly necessary.
  • Forgetting certificates and time zones. With scratch your application won’t be able to validate TLS unless you copy /etc/ssl/certs/ca-certificates.crt from the builder.
  • Using distroless without a debugging plan. Before migrating, define how you’ll diagnose incidents (ephemeral containers, structured logs, metrics).
  • Measuring size only. A small image with 200 unaudited dependencies is still a risk. Pair reduction with continuous scanning.
  • Ignoring disk size versus transfer size. The registry compresses layers; compare docker history and docker image inspect to understand what each layer actually takes up.

How to measure the 80% improvement

To make the change defensible, measure before and after:

docker images mi-api --format "{{.Repository}}:{{.Tag}} {{.Size}}"
docker history mi-api:latest
trivy image --severity HIGH,CRITICAL mi-api:latest

Document three metrics: final size, number of high and critical vulnerabilities, and pull time on a clean node. Typically, the first drops by 70% to 98%, the second shrinks dramatically, and the third improves in direct proportion to size. With those numbers, convincing your team to roll the practice out across every service is a one-meeting conversation.

Conclusion: the cheapest change with the biggest return

Multi-stage builds don’t require new tools, licenses or traumatic migrations. They ask you to reorganize a Dockerfile and embrace a simple idea: what isn’t needed to run doesn’t ship to production. In return you get faster deployments, lower costs, fewer CVEs and a container that, if someone compromises it, gives them very little to work with.

Start with your heaviest service, measure the result and replicate the pattern. If you want to dig into the official practices and the latest BuildKit features, the Docker documentation is the best place to start. Your registry, your cluster and your security team will notice from the very first deployment.

Keep reading