Skip to content

Multi-stage Docker build for Go Applications

A multi-stage build is a Docker technique used to optimize the size of the final container image by separating the build environment from the runtime environment^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md]. This is particularly useful for compiled languages like Go, where the build tools and source code are not required to execute the final binary.

Benefits

Using a multi-stage build for Go applications offers several advantages:

  • Reduced Image Size: The final runtime image does not include the Go compiler, source code, or module dependencies, resulting in a significantly smaller image^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].
  • Security: By excluding build tools and source code from the final image, the attack surface is minimized.

Implementation

A typical multi-stage Dockerfile for a Go application involves three distinct stages: development, building, and runtime^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

Stage 1: Development (Base)

The first stage defines the development environment. This typically uses the official Golang image and sets the working directory^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

FROM golang:1.15-alpine as dev

WORKDIR /work

Stage 2: Build

The second stage is responsible for compiling the application. It uses the Go environment to copy source code and build the executable binary^[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

Stage 3: Runtime

The final stage creates the production image. It starts with a minimal base image (such as Alpine Linux) and copies only the compiled binary from the build stage^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

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

Build and Execution

Once the Dockerfile is defined, the image can be built using the docker build command^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

docker build . -t videos

The resulting container can then be run, exposing the necessary ports and passing any required environment variables^[400-devops__09-Scripting-Language__golang__introduction__part-5.database.redis__readme.md].

docker run -it -p 80:80 videos
  • [[流程化筆記]]: Documentation practices can be applied to documenting the build and deployment process.
  • 20/80 Learning Principle: Understanding Docker basics (the 20%) is often sufficient to effectively deploy Go applications.

Sources

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