Skip to content
Tutorials Center
My learning

Topics

Lesson 84 of 111 ยท Language Recipes

Containerizing a Python App

Containerize a Python web app: slim images, a virtual environment copied between stages, gunicorn, bytecode and buffering settings, uv, a healthcheck and non-root.

Python is easy to containerize and easy to do wastefully. A beginner's Dockerfile installs packages as root into the system Python, drags a compiler toolchain into production, runs the Flask development server and prints logs that appear minutes late. None of that is hard to fix once you know the handful of settings that matter for Python specifically.

In this lesson you will containerize a small Flask API. You will use a slim base image, build dependencies in a virtual environment in one stage and copy it into a clean second stage, run the app with gunicorn as an unprivileged user, set the environment variables that every Python container should have, and then see how uv makes the install step faster. All outputs come from real builds with Python 3.13.

The app

TEXT
project/
  requirements.txt
  .dockerignore
  Dockerfile
  app/
    __init__.py
    main.py
TEXT
# requirements.txt
flask==3.1.2
gunicorn==23.0.0
Python
# app/main.py
import os

from flask import Flask, jsonify

app = Flask(__name__)


@app.get("/")
def index():
    return jsonify(message="Hello from a container", uid=os.getuid())


@app.get("/healthz")
def healthz():
    return "ok"

Pin exact versions (==) in requirements.txt. Ideally you pin every transitive dependency too, with a lock file produced by pip freeze, pip-tools or uv, so two builds a month apart install the same packages. The .dockerignore keeps local clutter out of the build context:

TEXT
__pycache__
*.pyc
.venv
.git
.env

Choosing the base image

The official python image comes in several flavors, as covered in Choosing a Base Image:

Tag Based on Size class Notes
python:3.13 Debian with build tools Large Compilers and headers included
python:3.13-slim Debian, minimal Medium (178 MB here) Best default for most apps
python:3.13-alpine Alpine (musl) Small Many wheels do not exist for musl, so installs can compile from source and be slow

-slim is the recommendation for Python. The Alpine variant looks tempting, but packages with C extensions (numpy, pandas, cryptography, psycopg) publish prebuilt "manylinux" wheels for glibc, not for musl. On Alpine pip may build them from source, which needs a compiler, takes minutes and makes the image bigger than the slim one would have been.

The Dockerfile

Here is the production Dockerfile, with two stages. The first creates a virtual environment and installs packages into it. The second starts from a clean slim image and copies only the finished environment.

DOCKERFILE
# syntax=docker/dockerfile:1
FROM python:3.13-slim AS builder
ENV PIP_DISABLE_PIP_VERSION_CHECK=1
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
WORKDIR /src
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install -r requirements.txt

FROM python:3.13-slim AS runtime
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PATH="/opt/venv/bin:$PATH"
RUN useradd --system --uid 10001 --no-create-home appuser
COPY --from=builder /opt/venv /opt/venv
WORKDIR /app
COPY app ./app
USER appuser
EXPOSE 8000
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s \
  CMD python -c "import urllib.request as u; u.urlopen('http://127.0.0.1:8000/healthz', timeout=2)" || exit 1
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "2", "app.main:app"]

Build it and look at the result:

CONSOLE
$ docker build -t py-app:1 .
$ docker images --format '{{.Repository}}:{{.Tag}} {{.Size}}' | grep -E 'py-app|python:3.13-slim'
py-app:1 203MB
python:3.13-slim 178MB

The finished image is the 178 MB base plus about 25 MB for Flask, gunicorn and their dependencies. Now the decisions, one by one.

Why a virtual environment?

Inside a container you do not need a venv for isolation, so why create one? Because it gives you one directory (/opt/venv) containing everything pip installed. Copying it between stages is a single COPY --from=builder. Installing into the system Python would scatter files across /usr/local/lib, /usr/local/bin and more, which is hard to move. PATH="/opt/venv/bin:$PATH" makes python, pip and gunicorn resolve to the venv without an activate script. (The venv is copied to the same path it was created at, which matters: venvs record absolute paths.)

The builder stage is where you would also install compilers and -dev packages if a dependency needs to compile. They stay behind in builder and never reach the runtime image. See Multi-Stage Builds.

The three environment variables

  • PYTHONUNBUFFERED=1 makes Python write stdout and stderr immediately instead of buffering when they are not a terminal. Without it, docker logs can lag far behind reality, and a crash can lose the last lines. It matters because Docker captures output through a pipe.
  • PYTHONDONTWRITEBYTECODE=1 stops Python from writing .pyc files next to your source at run time. The container's filesystem layers are mostly read-only anyway, and as a non-root user the app could not write there. Bytecode for installed packages was already compiled by pip during the build (the venv contained 593 .pyc files in our image), so start-up speed does not suffer.
  • PIP_DISABLE_PIP_VERSION_CHECK=1 stops pip from phoning home on every run.

Running as a non-root user

useradd --system --uid 10001 --no-create-home appuser creates an unprivileged account with a fixed UID, and USER appuser runs everything after that as it. A fixed numeric UID helps when you later match file ownership on volumes or use Kubernetes policies that require a non-root numeric user. Test it:

CONSOLE
$ docker run -d --name web -p 127.0.0.1:8000:8000 py-app:1
$ curl -s localhost:8000/
{"message":"Hello from a container","uid":10001}
$ docker exec web sh -c 'touch /app/x'
touch: cannot touch '/app/x': Permission denied

The app runs as UID 10001 and cannot modify its own code directory. See Users and Permissions.

gunicorn, not the development server

flask run and python app.py start the development server, which is single-process, not hardened and prints a warning that it is not for production. Use a production WSGI server instead: gunicorn for Flask and Django, or uvicorn (often under gunicorn with -k uvicorn.workers.UvicornWorker) for FastAPI and other ASGI apps. A read-only sketch for ASGI:

DOCKERFILE
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Bind to 0.0.0.0, not 127.0.0.1, or published ports cannot reach the server. The number of workers should match the CPU cores you give the container (a common starting point is 2 x cores + 1 for sync workers; for async servers, fewer). Because the CMD is in exec form, gunicorn is PID 1 and receives SIGTERM directly:

CONSOLE
$ docker logs web
[2026-10-23 15:17:09 +0000] [1] [INFO] Starting gunicorn 23.0.0
[2026-10-23 15:17:09 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1)
[2026-10-23 15:17:09 +0000] [1] [INFO] Using worker: sync
[2026-10-23 15:17:09 +0000] [7] [INFO] Booting worker with pid: 7
[2026-10-23 15:17:09 +0000] [8] [INFO] Booting worker with pid: 8
$ time docker stop web
web

real    0m2.6s
$ docker logs web 2>&1 | tail -4
[2026-10-23 15:17:19 +0000] [1] [INFO] Handling signal: term
[2026-10-23 15:17:19 +0000] [7] [INFO] Worker exiting (pid: 7)
[2026-10-23 15:17:19 +0000] [8] [INFO] Worker exiting (pid: 8)
[2026-10-23 15:17:19 +0000] [1] [INFO] Shutting down: Master

The master (PID 1) handled SIGTERM, told both workers to finish, and exited cleanly. That is graceful shutdown for free, because gunicorn already knows how (Signals, PID 1 and --init).

The health check

Slim images do not include curl, but they have Python. The health check uses urllib from the standard library. urlopen raises an exception for connection errors and for HTTP error statuses, so a failing app makes the command exit non-zero. After a few seconds:

CONSOLE
$ docker ps --filter name=web --format '{{.Names}} {{.Status}}'
web Up 11 seconds (healthy)

Layer order and the cache

Because requirements.txt is copied and installed before the application code, changing app/main.py does not reinstall anything. Edit a source file and rebuild:

CONSOLE
$ echo "# change" >> app/main.py
$ docker build -t py-app:2 . --progress=plain
...
#12 [builder 5/5] RUN --mount=type=cache,target=/root/.cache/pip     pip install -r requirements.txt
#12 CACHED
#13 [runtime 3/5] COPY --from=builder /opt/venv /opt/venv
#13 CACHED
#15 [runtime 5/5] COPY app ./app
#15 DONE 0.6s

Only the final copy of your code reruns. When you do change requirements.txt, the install reruns, but the pip cache mount means that packages already downloaded are reused instead of fetched again (Build Performance).

Faster installs with uv

uv is a Python package installer written in Rust that is much faster than pip. It works as a drop-in for the install step and can also manage projects and lock files. It ships as a small image that you can copy a binary out of:

DOCKERFILE
# syntax=docker/dockerfile:1
FROM python:3.13-slim AS builder
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
ENV UV_LINK_MODE=copy UV_COMPILE_BYTECODE=1
RUN uv venv /opt/venv
WORKDIR /src
COPY requirements.txt .
RUN --mount=type=cache,target=/root/.cache/uv \
    VIRTUAL_ENV=/opt/venv uv pip install -r requirements.txt

FROM python:3.13-slim AS runtime
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PATH="/opt/venv/bin:$PATH"
RUN useradd --system --uid 10001 --no-create-home appuser
COPY --from=builder /opt/venv /opt/venv
WORKDIR /app
COPY app ./app
USER appuser
CMD ["gunicorn", "--bind", "0.0.0.0:8000", "app.main:app"]

Two settings matter: UV_LINK_MODE=copy because the cache mount and the venv live on different filesystems (uv would otherwise try hard links and warn), and UV_COMPILE_BYTECODE=1 to precompile .pyc files at build time. In our test the install step took about 4.6 seconds with uv against 7.8 seconds with pip on a cold cache, and the image came out at 186 MB. The numbers depend on your network, but uv is consistently quicker. Pin the uv image to a version tag in real projects instead of latest.

If your project uses pyproject.toml and uv.lock, the commands become uv sync --frozen --no-dev (which installs exactly what the lock file says). That is the closest Python equivalent of npm ci and is shown here as a read-only sketch, because it needs a project layout beyond this lesson.

Common problems

  • A package fails to build. The error mentions gcc or a missing header. Install the build tools in the builder stage only (apt-get install -y --no-install-recommends build-essential libpq-dev) and the runtime library (libpq5) in the runtime stage.
  • The app starts but the port is unreachable. It is bound to 127.0.0.1. Bind to 0.0.0.0.
  • Logs appear late. PYTHONUNBUFFERED is missing.
  • ModuleNotFoundError in the runtime stage. PATH does not include /opt/venv/bin, or the venv was copied to a different path than it was created at.
  • Permission denied writing files. The app tries to write into its code directory as a non-root user. Use a volume with the right ownership or /tmp.
  • Secrets in the image. Read configuration from environment variables at run time (Configuring Containers).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the production Dockerfile install packages into a virtual environment in a builder stage and copy /opt/venv to the runtime stage?

    A venv collects everything pip installed in a single movable directory. Build tools and caches stay behind in the builder stage, so the runtime image is clean and smaller.
  2. 2. What does PYTHONUNBUFFERED=1 fix?

    When stdout is a pipe, as it is under Docker, Python buffers output. The variable turns the buffering off so logs arrive in real time and are not lost on a crash.
  3. 3. Why is python:3.13-slim usually a better choice than python:3.13-alpine?

    Prebuilt manylinux wheels target glibc. On Alpine (musl) pip may need a compiler and compile packages, which is slow and can make the final image larger.
  4. 4. You change only app/main.py and rebuild the multi-stage Dockerfile from this lesson. What happens to the pip install step?

    The install depends only on requirements.txt, which was copied before the application code. Only the later COPY app ./app layer is rebuilt.
  5. 5. What is wrong with running flask run --host 0.0.0.0 as the container command in production?

    The development server is single-process and not built for production. Use a production server such as gunicorn or uvicorn, with the container command in exec form so it receives signals directly.

Summary

  • Use python:3.13-slim as the default base; Alpine often forces slow source builds for packages with C extensions.
  • Build dependencies in a virtual environment in a builder stage, then COPY --from=builder /opt/venv into a clean runtime stage and put /opt/venv/bin on PATH.
  • Copy requirements.txt and install before copying the code, with a pip cache mount; pin exact versions.
  • Set PYTHONUNBUFFERED=1, PYTHONDONTWRITEBYTECODE=1 and PIP_DISABLE_PIP_VERSION_CHECK=1.
  • Run as a non-root user with a fixed UID, bind to 0.0.0.0, and use gunicorn or uvicorn instead of the development server; gunicorn as PID 1 shut down gracefully in 2.6 seconds.
  • Write the health check with urllib since slim images have no curl.
  • uv replaces pip for much faster installs (about 4.6 s against 7.8 s here); set UV_LINK_MODE=copy with a cache mount.

Next: Containerizing a Java App