Browse topics

Multi-stage builds

Version
29
Review
Draft

Summary#

Each FROM begins a new build stage. COPY --from takes chosen files from another stage, so compilers and source files can stay out of the final image. --target stops the build at a named stage.

Syntax#

dockerfile
FROM BUILD_IMAGE AS build
RUN build-command

FROM RUNTIME_IMAGE
COPY --from=build /path/to/artifact /destination

Example#

Use a disposable Docker daemon for this example. Discard its storage afterward to clear the build cache.

sh
(
  set -eu
  final="dlr-docker-commands-multistage:$$"
  debug="dlr-docker-commands-multistage:$$-build"
  name="dlr-docker-commands-multistage-$$"
  dir=$(mktemp -d)
  trap 'docker rm -f "$name" >/dev/null 2>&1 || true; docker image rm "$final" "$debug" >/dev/null 2>&1 || true; rm -rf -- "$dir"' EXIT

  printf 'pear\napple\n' > "$dir/fruit.txt"
  cat > "$dir/Dockerfile" <<'EOF'
FROM alpine:3 AS build
WORKDIR /src
COPY fruit.txt .
RUN sort fruit.txt > report.txt

FROM busybox:1 AS release
COPY --from=build /src/report.txt /report.txt
CMD ["sh", "-c", "cat /report.txt; test -e /src || echo 'no /src here'"]
EOF

  label="dlr-docker-commands-multistage=$$"
  docker build --quiet --label "$label" --tag "$final" "$dir" >/dev/null
  docker build --quiet --label "$label" --target build --tag "$debug" "$dir" >/dev/null

  echo "final image:"
  docker run --pull never --rm --name "$name" "$final"
  echo "build stage:"
  docker run --pull never --rm --name "$name" "$debug" ls /src
)

Expected output#

Text
final image:
apple
pear
no /src here
build stage:
fruit.txt
report.txt

Common mistakes#

A stage that starts from a separate base needs its runtime files copied explicitly. FROM build instead uses the build stage as its base and inherits its files. Check that any copied binary works with the libraries in the final base image.

Version applicability#

Checked with Docker Engine 29. BuildKit builds only the stages the target depends on. The legacy builder also processes earlier stages that the target does not need.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0