Cloud Native 5 min read

Practical Guide to Heterogeneous Image Builds and Multi‑Stage Dockerfile Optimization

This article explains heterogeneous Docker image builds, demonstrates how to name and reference multi‑stage build stages for clearer Dockerfiles, shows how to limit builds with the target flag for debugging, and illustrates copying files from existing images such as nginx to streamline container creation.

Practical DevOps Architecture
Practical DevOps Architecture
Practical DevOps Architecture
Practical Guide to Heterogeneous Image Builds and Multi‑Stage Dockerfile Optimization

Heterogeneous image builds refer to situations where the build environment is incompatible with the runtime environment, and multi‑stage builds offer additional capabilities beyond the basic usage.

By default, each build stage in a Dockerfile is unnamed and referenced by its order, but naming stages with the AS keyword improves readability and reduces the need to adjust COPY instructions when reordering or adding stages.

For example, the following Dockerfile can be optimized:

FROM golang:1.16 AS builder

WORKDIR /go/src/github.com/wilhelmguo/multi-stage-demo/

COPY main.go .

RUN CGO_ENABLED=0 GOOS=linux go build -o http-server .

FROM alpine:latest

WORKDIR /root/

COPY --from=builder /go/src/github.com/wilhelmguo/multi-stage-demo/http-server .

CMD ["./http-server"]

In the first stage, the AS builder clause names the stage, and the second stage copies the compiled binary using --from=builder , resulting in a clearer Dockerfile.

When a build stage is complex and you need to debug only the compilation step, you can stop the build at a specific stage with the --target option, e.g.:

docker build --target builder -t http-server:latest .

This command limits the build to the builder stage, speeding up debugging.

Multi‑stage builds also allow copying files from existing images. Using COPY --from , you can pull files from a local or remote image, such as copying the nginx configuration from the official nginx image:

COPY --from=nginx:latest /etc/nginx/nginx.conf /etc/local/nginx.conf

Other scenarios include extracting tools from pre‑built images when the required packages are unavailable or outdated in the current base image, enabling convenient reuse of compiled binaries.

【Please scan the QR code to follow and improve together】

Dockerci/cddevopsContainerMulti‑Stage BuildDockerfile
Practical DevOps Architecture
Written by

Practical DevOps Architecture

Hands‑on DevOps operations using Docker, K8s, Jenkins, and Ansible—empowering ops professionals to grow together through sharing, discussion, knowledge consolidation, and continuous improvement.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.