Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 122 of 8022. Docker Image LifecycleFree lesson

Copying Artifacts Between Build Stages

You will use the --from flag to selectively extract compiled binaries or static assets from a previous stage into your final image.

In this lesson, you will learn how to selectively pull only the files you need from a heavy build environment into a lightweight production image using the --from flag.

The Power of Selective Extraction

When you use multi-stage builds, the goal is often to separate the "kitchen" (where the cooking happens) from the "dining room" (where the meal is served). You don’t want your production image cluttered with source code, compilers, or heavy build tools that aren't needed to run the application.

The COPY instruction is your bridge between these stages. By adding the --from flag, you tell Docker: "Don't look in my local directory; look inside a specific stage of this build process."

How It Works

Imagine you have a builder stage where you compile a Go application into a single binary. Your final stage should only contain that binary. Here is how you perform that surgical extraction:

# Stage 1: The Kitchen (Build)
FROM golang:1.21 AS builder
WORKDIR /app
COPY . .
RUN go build -o my-app main.go

# Stage 2: The Dining Room (Production)
FROM alpine:latest
WORKDIR /root/
# Extract only the binary from the 'builder' stage
COPY --from=builder /app/my-app .
CMD ["./my-app"]

Why This Matters

If you copied the entire build directory, you would end up with source files, cache folders, and language runtimes (like the Go compiler) inside your production image. These add unnecessary weight and introduce security vulnerabilities.

By using COPY --from, you treat the previous stage as a temporary file system. You can reach in, grab just the my-app binary, and leave all the build-time "trash" behind. This results in an image that is significantly smaller, faster to deploy, and more secure, as it contains only the absolute minimum required to execute your code.

Key Takeaway: Use the --from flag with the COPY instruction to transfer only your compiled binaries or static assets from a build stage, ensuring your final production image remains lean and secure.