Skip to content

Docker multi-stage builds for Go

Docker multi-stage builds are an optimization technique used to create smaller, more secure container images by separating the build environment from the runtime environment.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

Structure

A multi-stage build Dockerfile uses multiple FROM statements to define distinct stages, typically named dev (or builder) and runtime.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

  1. Build Stage: Uses a full Go SDK image (e.g., golang:1.15-alpine) to compile the application source code.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]
  2. Runtime Stage: Uses a lightweight base image (e.g., alpine) and copies only the compiled binary from the build stage using the COPY --from=<stage> syntax.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

This process ensures that the final image contains only the necessary application binary and runtime dependencies, excluding the Go toolchain, source code, and build artifacts.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

Example Dockerfile

The following example demonstrates a build pipeline that compiles a Go application and outputs a minimal Alpine-based image.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

FROM golang:1.15-alpine as build

WORKDIR /videos
COPY ./videos/* /videos/
RUN go build -o videos

FROM alpine as runtime 
COPY --from=build /videos/videos /
CMD ./videos

Build and Run

The build process targets the final image by default, producing a container ready for deployment.^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]

Build command:

docker build . -t videos

Run command:

docker run -it -p 80:80 videos

  • [[Docker]]
  • [[Go]]
  • [[Containerization]]

Sources

  • 400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md