Monk CIMonk CI home

3 Dec, 2026Himanshu Sharma

Docker Multi-Stage Builds: A Working Example


Create a Docker multi-stage build that keeps compiler tools out of the runtime image, copies only required output, and verifies the final container runs.

A Docker multi-stage build uses separate stages for building and running an application. Compile or assemble the application in one stage, then copy only its required output into the final stage with COPY --from.

The goal is a deliberate runtime image. Removing build tools can reduce unnecessary contents, but the final image still needs every library, certificate, configuration file and permission the application requires.

How do named stages work?

Each FROM begins a stage. A name such as build makes references readable when stages are added or reordered.

Diagram for Docker Multi-Stage Builds: A Working Example
Diagram for Docker Multi-Stage Builds: A Working Example

Only the files you copy across become part of the final stage's filesystem, together with that stage's base image and subsequent instructions. Docker's multi-stage reference explains stage names, targets and copying outputs.

What does a complete working example look like?

This tiny C program makes the build/runtime separation visible without an application framework. Put hello.c and the Dockerfile in a new directory.

#include <stdio.h>

int main(void) {
    puts("multi-stage-ok");
    return 0;
}
FROM alpine:3.22 AS build
RUN apk add --no-cache build-base
WORKDIR /src
COPY hello.c .
RUN mkdir -p /out && cc -static -Os -s -o /out/hello hello.c

FROM scratch AS runtime
COPY --from=build /out/hello /hello
USER 65532:65532
ENTRYPOINT ["/hello"]

The compiler and source stay in the build stage. The final stage contains the statically linked program. 65532 is an example non-root numeric identity, not a required Docker user ID. The Alpine version is an example base selection; maintain and pin the image according to your update policy.

Build and smoke-test the result:

docker build -t article-multistage:local .
docker run --rm article-multistage:local
docker image inspect article-multistage:local \
  --format '{{.Config.User}} {{json .Config.Entrypoint}}'

The program should print multi-stage-ok and exit successfully. This is a functional example, not a claim about how much smaller or faster your production image will become.

Why can this example use scratch?

The program is deliberately statically linked and performs no network, certificate or timezone-dependent work. scratch contributes no operating-system filesystem, so there is no shell or package manager to fill missing dependencies later.

Application requirementRuntime decision
Dynamic system librariesChoose a compatible runtime base or include required libraries deliberately
TLS connectionsSupply the relevant certificate trust store
User or group name lookupSupply appropriate identity files or use compatible numeric identities
Writable temporary filesProvide writable paths with correct ownership
Shell-based startup scriptInclude the shell or use an executable entrypoint

Do not copy this scratch stage onto a Node.js or Python application and expect it to run. Those applications ordinarily need their runtime and potentially native-library dependencies. Start from the runtime contract, then choose the smallest appropriate base.

How do you inspect an intermediate stage?

Build a named target when you need to inspect the build environment. Keep that diagnostic image separate from the final deliverable.

docker build --target build -t article-multistage:build .
docker run --rm article-multistage:build /out/hello

The target image intentionally includes build tools. This is useful for diagnosis but is not the image named article-multistage:local from the final-stage build. Make the target and tag explicit in CI so a diagnostic image is not published accidentally.

Does a multi-stage Dockerfile improve caching?

Stage separation and cache invalidation are related design choices, but they solve different problems. A multi-stage file can still invalidate expensive work if it copies changing inputs before dependency installation.

In the example, the source copy follows tool installation. In a real project, isolate dependency manifests and lockfiles before copying frequently changing source. Follow the Dockerfile ordering guide and measure the phases described in speeding up Docker builds.

Docker's build best practices also cover trusted bases, build context and image maintenance. For private dependencies, use build secret mounts; hiding a credential in an earlier stage is not a substitute for proper secret handling.

How should you verify a production image?

Test the actual final image, not just the build stage. A successful compiler command does not establish that the runtime image is deployable.

  1. Run its normal entrypoint and assert the expected exit or readiness behavior.
  2. Exercise important filesystem, network and certificate paths.
  3. Check runtime architecture, user and writable-directory permissions.
  4. Run the repository's integration checks against this image.
  5. Inspect and scan the deliverable before publishing it.

Monk CI can run the workflow that performs these checks; its builder integration does not remove the need for them. Keep the same smoke and integration tests when moving builds between providers.

Frequently asked questions

Does copying from another stage copy every file in that stage?

No. COPY --from copies the source path you specify into the destination path. Choose that path narrowly and inspect the resulting filesystem. Copying an entire build directory can reintroduce source files, development dependencies or configuration that you intended to leave behind in the build stage.

Can I run a shell in the final scratch image?

Not unless you explicitly included one. The example contains only its executable, so a command that expects sh will fail. Diagnose the build stage separately, and use application-level checks or a suitable debugging image rather than assuming every production container includes standard shell utilities.

Do multi-stage builds guarantee a secure image?

No. Reducing unnecessary tools can reduce the contents you maintain, but vulnerabilities can remain in the application, libraries or base image. Keep dependency updates, image scanning, least-privilege execution and runtime checks. Stage separation is one packaging technique within that work, not a security certification.

Will the final image always be smaller?

No universal reduction is implied. It depends on the original image, selected runtime base and files copied forward. Compare the actual deliverables with their functionality held constant. Report measured sizes and build conditions when making a claim, rather than applying a percentage from an unrelated example.

Try Monk CI for free

Continue with GitHub