Docker multi-stage build¶
A Docker multi-stage build is a technique that allows a developer to use multiple FROM statements in a single Dockerfile.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md] Each FROM instruction begins a new stage of the build, enabling the separation of build dependencies from runtime environments.
Structure and Phases¶
In a multi-stage build workflow, the Dockerfile is typically divided into distinct logical phases, such as a development environment, a build environment, and a runtime environment.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md]
- Dev Stage: The initial stage often sets up the language environment and workspace, such as
FROM golang:1.15-alpine as dev, which establishes a working directory for development.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md] - Build Stage: A dedicated stage is used to compile the application. This stage copies source code and executes build commands, like
go build -o videos, to generate the executable binary.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md] - Runtime Stage: The final stage creates a small, production-ready image. It typically starts from a minimal base image, such as
alpine, and uses theCOPY --from=directive to retrieve only the compiled artifacts from the previous build stage, omitting source code and build tools.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md]
Benefits¶
The primary advantage of this method is the reduction of the final image size. By compiling the application in an intermediate stage and copying only the resulting binary to the final runtime stage, the final image contains only what is necessary to run the application, rather than the entire toolchain required to build it.^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md]
Related Concepts¶
- [[Docker]]
- [[Golang]]
- CI/CD
Sources¶
^[400-devops-09-scripting-language-golang-introduction-part-5databaseredis-readme.md]