Docker multi-stage builds for Go applications¶
Docker multi-stage builds are a technique used to optimize the size of the final container image for Go applications by separating the build environment from the runtime environment^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].
In Go development, the build process requires the full Go compiler and source code, but the resulting binary is a statically linked executable that can run on a minimal operating system. Multi-stage builds leverage this by using one image to compile the code and a smaller, lighter image to run it^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].
Build stages¶
The build process is defined in a Dockerfile using multiple FROM instructions. Each FROM instruction begins a new stage, and stages can be named using the as alias syntax^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].
- Development Stage: The first stage, often named
dev, sets up the workspace and contains the necessary tooling (like the Go SDK) for compilation^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md]. - Build Stage: A second stage (e.g.,
build) handles the actual compilation of the source code into a binary executable^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].
Runtime stage¶
The final stage defines the actual container that will be deployed. This stage typically starts from a minimal base image, such as alpine, which is much smaller than a full Go SDK image^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].
To populate this image, the COPY --from instruction is used to retrieve artifacts—specifically the compiled binary—from a previous stage^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md]. This ensures the final image contains only the application binary and necessary data files, excluding the source code and build tools.
Example Workflow¶
In a typical setup, the Docker build process follows these steps:
- Compile: The
buildstage copies source code and runsgo build -o <name>to create the executable^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md]. - Transfer: The
runtimestage copies the compiled binary from the/videos/directory in thebuildstage to its root directory^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md]. - Execute: The
CMDinstruction is set to run the binary directly^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md].
Related Concepts¶
- [[Docker]]
- Go modules
- [[Microservices]]
Sources¶
^[400-devops__09-Scripting-Language__golang__introduction__part-3.http__readme.md]