Skip to content

Docker multistage builds for Python

Docker multistage builds allow you to use multiple FROM statements in a single Dockerfile to create separate stages for the build lifecycle.^[400-devops__09-Scripting-Language__python__introduction__README.md] This technique enables the creation of distinct environments for development and production within the same image definition.

Build Stages

In a typical Python workflow, you might define three distinct stages to separate concerns:^[400-devops__09-Scripting-Language__python__introduction__README.md]

  1. Development (dev): A base stage used to run Python in an isolated environment.^[400-devops__09-Scripting-Language__python__introduction__README.md]
  2. Debugging (debugging): An optional layer that extends the development environment to include debuggers and extra tooling that should not be present in production.^[400-devops__09-Scripting-Language__python__introduction__README.md]
  3. Runtime (runtime): A minimal stage containing only the Python interpreter and the application source code intended for production execution.^[400-devops__09-Scripting-Language__python__introduction__README.md]

Implementation Example

The following Dockerfile demonstrates this structure using python:3.9.6-alpine3.13 as the base image.^[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" ]

Usage

To build the image using the multistage configuration, use the standard build command.^[400-devops__09-Scripting-Language__python__introduction__README.md]

docker build . -t customer-app

You can run the resulting production container with:^[400-devops__09-Scripting-Language__python__introduction__README.md]

docker run customer-app

For development, you can build a specific target stage to keep the source code mounted rather than copied, facilitating live coding and testing.^[400-devops__09-Scripting-Language__python__introduction__README.md]

docker build --target dev . -t python
docker run -it -v ${PWD}:/work python sh

Sources

^[400-devops__09-Scripting-Language__python__introduction__README.md]