3.3.2.3 Python Runtime Images
A focused guide to Python Runtime Images, connecting core concepts with practical Docker and container operations.
Python runtime images provide the Python interpreter pre-installed on top of an operating system base, serving as the standard foundation for containerizing Python applications, with variants balancing image size against compatibility for compiled dependencies.
Basic Python Application Containerization
A typical Python Dockerfile installs dependencies from a requirements file, copies the application source, and runs it with the included interpreter.
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["python", "app.py"]
Choosing Between Full, Slim, and Alpine Variants
The full Python image includes broader system tooling useful during development; the slim variant strips much of this for a smaller production image, while the Alpine variant is smaller still but uses musl instead of glibc, which can complicate installing certain compiled Python packages that ship pre-built glibc wheels.
FROM python:3.12
FROM python:3.12-slim
FROM python:3.12-alpine
For dependencies with C extensions, the slim (glibc-based) variant is often a safer default than Alpine, unless compatibility has been explicitly verified.
Avoiding Unnecessary Cache Bloat
Pip caches downloaded packages by default, which adds unnecessary size to an image layer unless explicitly disabled, since the cache provides no benefit once the dependencies are already installed inside the image.
RUN pip install --no-cache-dir -r requirements.txt
Multi-Stage Builds for Compiled Dependencies
When dependencies require compilation, a multi-stage build can perform that compilation in a fuller image while keeping the compiler and build headers out of the final runtime image.
FROM python:3.12 AS build
RUN apt-get update && apt-get install -y gcc python3-dev
COPY requirements.txt .
RUN pip wheel -r requirements.txt -w /wheels
FROM python:3.12-slim
COPY --from=build /wheels /wheels
RUN pip install --no-index --find-links=/wheels -r requirements.txt
Why Python Runtime Images Matter
Official Python runtime images provide a consistent, well-maintained starting point across the many ways Python applications might be containerized, with the choice of variant offering a clear, well-understood tradeoff between image size and dependency compatibility.