Lorixen.
EN

Docker multi-stage builds: smaller, safer app images

Short answer: A multi-stage Dockerfile builds your app in one stage that has all the compilers and tools, then copies only the finished output into a small final stage. The build tools, source files and caches stay behind, so the image you ship is smaller, faster to pull and has fewer packages to patch. Most apps need two or three stages, a .dockerignore file and a clear rule about what the final stage is allowed to contain.

Why images get so big in the first place

A typical first Dockerfile starts from a full language image, copies the whole project in, installs every dependency and runs the build. It works, but everything used along the way ends up in the image you deploy: the compiler, development dependencies, test fixtures, the package manager's cache and sometimes the .git folder.

That has real costs for a small business app:

  • Slower deploys. Every new server, autoscaled container or CI runner has to download the whole thing.
  • More to patch. Each extra package is something a security scanner can flag, even if your app never uses it at runtime.
  • Accidental leaks. Files copied in for the build, such as a local .env, can end up baked into a layer.

Multi-stage builds fix the first two directly and make the third much easier to control.

How a multi-stage build works

Docker's documentation describes the idea simply: you use several FROM statements in one Dockerfile, each starting a new stage, and you selectively copy artifacts from one stage to another, leaving behind everything you don't want in the final image.

A Node.js web app might look like this:

FROM node:22 AS build
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

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

The first stage, named build, has everything needed to compile. The second stage starts from a slimmer base and copies in only the production dependencies and the built files with COPY --from=build. The version numbers here are illustrative; pin whatever your app actually runs on.

Naming stages with AS matters more than it looks. Docker lets you refer to stages by number, but names survive someone inserting a new stage later.

Pick the final base image deliberately

The final stage decides most of the image size, so choose its base on purpose:

  • Slim variants of official language images keep the runtime but drop many build tools. They suit most interpreted apps, such as Node.js, Python and Ruby.
  • Minimal or distroless-style images contain little beyond the runtime. They're smaller still, but there's no shell for debugging inside a running container.
  • scratch, an empty image, works for statically compiled binaries, such as many Go programs. Docker's own multi-stage example copies a single Go binary into scratch.

Smaller isn't automatically better. If your team relies on opening a shell in a container to diagnose problems, a distroless image will slow that down. Decide what you need in production, then pick the smallest base that provides it.

Keep junk out of the build context

A multi-stage build controls what reaches the final image, but the build stage still receives everything you send it. Docker's build best-practices page recommends a .dockerignore file to exclude files that aren't relevant to the build. A sensible starting list:

.git
node_modules
.env
*.log
coverage

This speeds up builds, because less is sent to the builder, and it keeps local secrets out of every stage. If the build itself needs a secret, such as a private package token, use Docker's build secret mounts rather than COPY or ARG, so the value isn't stored in a layer.

Use stages for more than just shrinking

Once you think in stages, a few other patterns become easy:

  • A shared base stage. Put common setup, such as system packages, in one stage and build other stages FROM it. Docker's docs show this reuse pattern.
  • A test stage. Add a stage that runs your test suite against the build output. Run it in CI with docker build --target test, and leave it out of the production build.
  • A development stage. Keep a stage with debugging tools for local work, and build the production stage for deployment.

Docker documents the --target flag for building up to a specific stage. With BuildKit, only the stages the target depends on are built, so an unused test stage doesn't slow down production builds.

Order steps so the cache helps you

Layer caching is where multi-stage builds pay off day to day. Copy the dependency manifest, such as package.json and the lockfile, and install dependencies before copying the rest of the source. Then a change to one source file reuses the cached dependency layer instead of reinstalling everything.

The same rule applies in every stage: put things that change rarely near the top and things that change often near the bottom.

Check what you actually ship

After switching, verify the result instead of assuming it:

  1. Compare sizes with docker image ls before and after.
  2. Inspect layers with docker history <image> to see what each step added.
  3. Run the container and exercise the app, especially anything that loads files at runtime, such as templates, fonts or migrations, which are easy to forget in the copy step.
  4. Run your usual image scanner and compare the number of findings.

A worked example

Take a hypothetical Austin bakery-ordering app built with Node.js. Its single-stage image included the build toolchain, test files and the full dependency tree. The team split the Dockerfile into build, test and runtime stages, added a .dockerignore, and ran as the non-root node user in the final stage. Deploys got quicker because servers pulled a much smaller image, and the security scan had fewer packages to report. The one bug they hit was a missing email-template folder, which they fixed by adding a second COPY --from=build line.

FAQ

Do multi-stage builds work with Docker Compose?

Yes. Compose builds from your Dockerfile and can pick a stage with the target option, so you can use a development stage locally and the runtime stage in production.

Will my CI pipeline need changes?

Usually not. A normal docker build builds the last stage. You only add --target if you want to build or test a specific stage.

Is Alpine always the best final base?

Not always. It's small, but it uses a different C library, which can cause problems with some native modules. Test your app on it before committing.

Does this make the image secure by itself?

No. It removes unneeded packages, which helps. You still need to update base images, avoid running as root and keep secrets out of the build.

If your app's Docker image has grown slow and heavy, send us your Dockerfile and we'll suggest the stages.

Sources

WhatsAppBook a call