Docker multi-stage builds¶
Docker multi-stage builds are a technique used to optimize the size and efficiency of Docker images by separating the build environment from the runtime environment^[400-devops-03-containerization-docker.md].
Overview¶
In a multi-stage build, a single Dockerfile contains multiple FROM instructions^[400-devops-03-containerization-docker.md]. Each FROM instruction begins a new build stage, allowing the developer to copy artifacts—such as compiled binaries—from one stage to another while discarding the unnecessary build tools and source code used in earlier stages^[400-devops-03-containerization-docker.md].
Key Components¶
The process relies on naming stages using the as keyword and utilizing the --from flag to transfer files^[400-devops-03-containerization-docker.md].
Stage Naming¶
Stages are explicitly named to make them easier to reference. For example, FROM golang:1.18-alpine as dev defines a stage named dev^[400-devops-03-containerization-docker.md]. This allows subsequent stages to target specific previous stages.
Artifact Transfer¶
Files are copied between stages using the COPY --from syntax^[400-devops-03-containerization-docker.md]. For instance, COPY --from=build /app/app / copies the compiled application from the build stage into the current stage's root directory. This ensures that only the final executable is included in the runtime image.
Common Workflow¶
A typical multi-stage build workflow involves three distinct stages^[400-devops-03-containerization-docker.md]:
- Development (Dev): Contains the full toolchain (e.g., a compiler) and source code needed to build the application^[400-devops-03-containerization-docker.md].
- Build: Compiles the source code into a binary or executable artifact^[400-devops-03-containerization-docker.md].
- Runtime: Uses a minimal base image (such as
alpine) and includes only the artifacts copied from the build stage, resulting in a small final image^[400-devops-03-containerization-docker.md].
Advantages¶
- Reduced Image Size: By excluding build tools and source code from the final image, the overall size is significantly reduced^[400-devops-03-containerization-docker.md].
- Improved Security: A smaller attack surface is achieved by removing unnecessary packages and compilers from the production runtime^[400-devops-03-containerization-docker.md].
Related Concepts¶
- [[Docker]]
- CI/CD Pipelines
- [[Containerization]]
Sources¶
^[400-devops-03-containerization-docker.md]