Docker multi-stage build for Python¶
A Docker multi-stage build is a technique used to optimize Docker images by separating the build environment from the runtime environment.^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md] This approach is particularly useful in Python development to create lean production images while managing dependencies during the build process.
Implementation¶
To implement a multi-stage build, the Dockerfile uses multiple FROM statements, each initiating a new build stage.^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md]
Defining Stages¶
The following example defines an initial stage named dev using a Python image, followed by a final runtime stage:
FROM python:3.9.6-alpine3.13 as dev
WORKDIR /work
FROM dev as runtime
COPY ./src/ /app
ENTRYPOINT [ "python", "/app/app.py" ]
^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md]
- Build Stage (
dev): The first stage uses theas devsyntax to name the stage.^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md] This stage can contain compilers, build tools, or development dependencies that are not required for the application to run. - Runtime Stage (
runtime): The second stage copies only the necessary artifacts (such as compiled code or application scripts) from the previous stage or the host.^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md] In the example, it copies source code into/appand sets the entry point for the application.
Usage¶
When building the image, you can target a specific stage using the --target flag.^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md]
docker build --target dev . -t python
^[400-devops__09-Scripting-Language__python__introduction__part-3.json__README.md]
This command is useful for development workflows, allowing the creation of an image that includes development tools, whereas the default build produces the optimized runtime image.
Related Concepts¶
- Dockerfile
- [[containerization|Containerization]]