Skip to content
Latchkey

pip "externally-managed-environment" in a Docker Base Image

A RUN pip install in a Dockerfile fails because the base image (Debian 12, Ubuntu 24.04) marks its system Python as externally managed under PEP 668. The fix is to install into a venv baked into the image, not to fight the marker.

What this error means

A Docker build step RUN pip install ... aborts with error: externally-managed-environment. The same Dockerfile worked on an older base image that predated PEP 668.

docker build output
Step 4/8 : RUN pip install -r requirements.txt
 ---> Running in 8f1c...
error: externally-managed-environment
× This environment is externally managed

Common causes

PEP 668 base image (debian/ubuntu/python-slim on Debian)

Recent Debian/Ubuntu and the *-slim Python images built on them ship the EXTERNALLY-MANAGED marker, so a global pip install is blocked by design.

Installing into the system Python in the image

A Dockerfile that runs pip install against /usr/bin/python3 hits the marker. The official python:3.x (non-slim Debian) images do not set it, which is why some builds suddenly broke after a base bump.

How to fix it

Create and use a venv in the image (recommended)

Build a venv and put it first on PATH so every later layer and the runtime use it.

Dockerfile
FROM debian:12-slim
RUN apt-get update && apt-get install -y python3 python3-venv && rm -rf /var/lib/apt/lists/*
RUN python3 -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"
RUN pip install -r requirements.txt

Or override on the throwaway image layer

A built image is disposable, so the override flag is acceptable here if you do not want a venv.

Dockerfile
RUN pip install --break-system-packages -r requirements.txt

How to prevent it

  • Bake a venv into images on PEP 668 bases and put it on PATH.
  • Use the official python:3.x image when you want a non-PEP-668 base.
  • Keep the install pattern identical across base bumps by always using a venv.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →