Multi-stage Docker build¶
A Multi-stage Docker build is a technique used to optimize the size and efficiency of Docker images by separating the build environment from the runtime environment.^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]
Mechanism¶
In a standard multi-stage build, the Dockerfile contains multiple FROM instructions^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]. Each FROM instruction begins a new stage of the build^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]. Artifacts, such as compiled binaries, can be copied from one stage to another using the COPY --from directive^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]. This allows the final image to include only the necessary application files and runtime dependencies, discarding the source code, compilers, and build tools used in earlier stages.
Example¶
The following example demonstrates a multi-stage build for a Go application.^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]
- Builder Stage: Uses
golang:1.18-rc-alpineas the base image, sets the working directory, copies source code, and compiles the application into a binary namedmain^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]. - Final Stage: Uses a lightweight
alpine:3.15.0-rc.4image and copies only the compiled binary from the builder stage usingCOPY --from=builder /main .^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md].
This results in a final image that contains only the compiled application and the minimal Alpine OS, rather than the entire Go toolchain^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md].
Related Concepts¶
- Kubernetes
- [[Containerization]]
Sources¶
^[400-devops__06-Kubernetes__k8s-ithelp__Day6__README.md]