Python - virtualenv & Dockerfiles
Updated 2026-10-02: reworked for PEP 668, which changes the answer.
I recently saw a Dockerfile based on the official docker Debian image that was installing dependencies into a virtualenv.
At first I figured it didn’t need one, because the image has no system Python to isolate from:
$ docker run -it debian /bin/bash
root@21ca17310079:/# python
bash: python: command not found
A Dockerfile that needs Python has to apt-get install python3, though, and since Debian 12 that Python is marked externally managed (PEP 668), so pip refuses to install into it outside a virtualenv (error: externally-managed-environment). The virtualenv was the right call:
FROM debian
RUN apt-get update && apt-get install -y python3-venv
RUN python3 -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
COPY requirements.txt .
RUN pip install -r requirements.txt
The official python image doesn’t need this, since it builds its own Python under /usr/local without the marker.