Docker multi-stage builds

Topic: Containers core

Summary

Use multiple FROM stages to build in one stage and copy artifacts into a smaller final image. Reduces size and keeps build tools out of production. Use when build needs compilers not needed at runtime.

Intent: How-to

Quick answer

  • First stage FROM image AS builder; RUN build. Second stage FROM minimal; COPY --from=builder /path/binary .
  • Only final stage is in the image. Use --from=name or --from=0.
  • Name stages with AS. Use .dockerignore to speed builds.

Prerequisites

Steps

  1. Builder stage

    FROM image AS builder; install deps; RUN build. Leave artifact in known path.

  2. Final stage

    FROM minimal_image; COPY --from=builder /path/artifact . CMD or ENTRYPOINT.

  3. Build

    docker build -t app . docker images to check size.

Summary

Multi-stage: build in one stage, copy artifact to final image. Smaller and safer.

Prerequisites

Steps

Step 1: Builder stage

FROM AS builder; build; leave artifact.

Step 2: Final stage

FROM minimal; COPY —from=builder; set CMD.

Step 3: Build

Build and check image size.

Verification

  • Image runs and is smaller.

Troubleshooting

Copy not found — Check path. Build fails — Fix builder deps.

Next steps

Continue to