Feedback

Chat Icon

Painless Docker - 2nd Edition

A Comprehensive Guide to Mastering Docker and its Ecosystem

Optimizing Docker Builds: Everything You Need to Know
34%

Optimizing Docker Builds: The Multi-Stage Build

You may ask the question: "If Docker uses the underlying Kernel of the host OS, why do we need the base image at all?" The answer is that the base image provides the necessary user-space libraries, tools, and environment for your application to run. For example, a Python application needs the Python interpreter and standard libraries, which are provided by the Python base image. When we run a container on a host that has no Python installed, the container can still run because it has its own user-space environment provided by the base image.

You may also wonder: "If the application is a static binary that includes all its dependencies, why do we need a base image?" This question is valid, and in such cases, we can use the scratch base image, which is an empty image.

This example will work with a simple static binary:

FROM scratch
COPY my-static-binary /my-static-binary
CMD ["/my-static-binary"]

In our previous Go example, we needed a base image because we used the Go toolchain to build the application and create the binary. The Go base image provided the necessary tools and libraries to compile the Go code, not to run the resulting binary. In this very specific case, we could have used a multi-stage build to create a smaller final image that only contains the static binary. This would take 2 steps:

  • First stage: Use the Go base image that includes the build tools to compile the Go application.
  • Second stage: Use the scratch base image to create a minimal final image that only contains the compiled binary.

To do this, let's create a multi-stage Dockerfile:

# cd to the application directory
cd $HOME/my-golang-app

cat << 'EOF' > Dockerfile
# First stage: Build the Go application
FROM golang:1.25-trixie AS builder
WORKDIR /app
ADD . /app
RUN go mod init my-golang-app
RUN go build -o main .

# Second stage: Create the final image with the static binary

Painless Docker - 2nd Edition

A Comprehensive Guide to Mastering Docker and its Ecosystem

Enroll now to unlock all content and receive all future updates for free.

Unlock now  $31.99$25.59

Hurry! This limited time offer ends in:

To redeem this offer, copy the coupon code below and apply it at checkout:

Learn More