0
0
Dockerdevops~30 mins

Why multi-stage builds reduce image size in Docker - See It in Action

Choose your learning style9 modes available
Why Multi-Stage Builds Reduce Image Size
📖 Scenario: You are working on a Docker project where you want to create a small and efficient container image for a simple Go application. You want to learn how multi-stage builds help reduce the final image size by separating build and runtime environments.
🎯 Goal: Build a Dockerfile using multi-stage builds that compiles a Go program in one stage and copies only the compiled binary to a smaller base image in the final stage. This will show how multi-stage builds reduce image size.
📋 What You'll Learn
Create a Dockerfile with two stages: a build stage and a final stage
Use golang:1.20 as the build stage base image
Compile a Go program called hello.go in the build stage
Use alpine:latest as the final stage base image
Copy only the compiled binary from the build stage to the final stage
Set the container to run the compiled binary
💡 Why This Matters
🌍 Real World
Developers often need to create small, efficient Docker images to save bandwidth and speed up deployment.
💼 Career
Understanding multi-stage builds is important for DevOps roles to optimize container images and improve CI/CD pipelines.
Progress0 / 4 steps
1
Create the Go source file
Create a file named hello.go with a simple Go program that prints "Hello, Docker!" when run. The program should have a main package and a main function with fmt.Println("Hello, Docker!").
Docker
Need a hint?

Use package main and import fmt. The main function should print the message.

2
Set up the build stage in Dockerfile
In a file named Dockerfile, create the first stage called builder using the base image golang:1.20. Copy the hello.go file into the container at /app/hello.go and set the working directory to /app. Add a command to build the Go program into a binary named hello.
Docker
Need a hint?

Use FROM golang:1.20 AS builder to name the build stage. Use WORKDIR and COPY to prepare files. Use RUN go build -o hello hello.go to compile.

3
Add the final stage to copy the binary
In the same Dockerfile, add a final stage using the base image alpine:latest. Copy the compiled binary hello from the builder stage to /hello in the final image. Set the container to run /hello when started.
Docker
Need a hint?

Use FROM alpine:latest for the final stage. Copy the binary with COPY --from=builder. Use CMD ["/hello"] to run the program.

4
Build and run the Docker image to see the output
Build the Docker image with the tag hello-multistage using the command docker build -t hello-multistage .. Then run the container with docker run --rm hello-multistage and observe the output.
Docker
Need a hint?

Use docker build -t hello-multistage . to build and docker run --rm hello-multistage to run the container.