Mike Barkas

Software Technologies

Mike Barkas

Mike Barkas

Software Technologies

Multistep Docker Image builds

May 10, 2024

Size is important when using container images, as well as security. To help address this you can build your own container images using a multistep process to build your final image.

Each step during the multistep build will do a specific task and the final image can use the artifacts built in the previous step.

Below are two examples of a Dockerfile using multistep container image builds. The idea is to reduce the image size, but more importantly remove software not used. This helps with the security of your application.


Each FROM declaration creates a new build step.


Python

Scripting language example:

  1. The “base” image has pip and installs what you need with requirements.txt
  2. The final image will only have the needed libraries and your app file(s)
# First step
# Name this step so it can be used in the next step
FROM cgr.dev/chainguard/python:latest-dev as base
WORKDIR /app
# Install only the required software for your app
COPY requirements.txt .
RUN pip install -r requirements.txt --user

# Second step
# Use the smallest image needed for your app
FROM cgr.dev/chainguard/python:latest
WORKDIR /app
# Copy from previous step "base"
COPY --from=base /installed/files/directory /installed/files/directory
COPY . ./
EXPOSE 8081
ENTRYPOINT ["python", "/app/app.py"]

Golang

Compiled language example:

  1. The “build” step has Go and tooling and does the build
  2. The final image only has the compiled binary for your app
# First step
# This step named "build"
FROM golang:1.21 as build
WORKDIR /
COPY go.mod go.sum ./
RUN go mod download
COPY main.go ./
RUN CGO_ENABLED=0 GOOS=linux go build main.go

# Second step
# Use the smallest image needed for your app
FROM alpine:3.18
WORKDIR /
# Copy from previous step "build"
COPY --from=build /main /main
EXPOSE 8080
ENTRYPOINT ["/main"]

Your final image should be as small as possible and only contain the needed files to run your application.

Always check where you pull your images FROM.