Skip to content

Docker multistage builds

Docker multistage builds allow a user to define multiple stages within a single Dockerfile, typically starting with a full-featured environment for development and ending with a minimal image for production^[400-devops-09-scripting-language-python-introduction-readme.md].

Structure and Syntax

This feature allows a user to select a specific base image as a named target for different purposes, such as development, debugging, or runtime^[400-devops-09-scripting-language-python-introduction-readme.md].

In a Dockerfile, this is implemented by adding the as <name> modifier to the FROM instruction^[400-devops-09-scripting-language-python-introduction-readme.md].

FROM python:3.9.6-alpine3.13 as dev
WORKDIR /work

FROM python:3.9.6-alpine3.13 as debugging
# add a debugger

FROM dev as runtime
COPY ./src/ /app 
ENTRYPOINT [ "python", "/app/app.py" ]

^[400-devops-09-scripting-language-python-introduction-readme.md]

Use Cases

Development and Debugging

A primary use case is creating a dedicated stage for the development environment^[400-devops-09-scripting-language-python-introduction-readme.md]. In this stage, a user might simply mount source code to gain access to a Python environment^[400-devops-09-scripting-language-python-introduction-readme.md].

An intermediate stage can be created specifically for debugging^[400-devops-09-scripting-language-python-introduction-readme.md]. This stage allows for the installation of debuggers and other extra development tools that are not intended to be present in the final production image^[400-devops-09-scripting-language-python-introduction-readme.md].

Production Runtime

The final stage produces a minimal image containing only the application source code and the necessary runtime (e.g., Python)^[400-devops-09-scripting-language-python-introduction-readme.md].

This approach results in a smaller runtime image because it excludes the unnecessary build tools and debuggers included in previous stages^[400-devops-09-scripting-language-python-introduction-readme.md].

Sources

  • 400-devops-09-scripting-language-python-introduction-readme.md