Python “This environment is externally managed” Error and Docker

Elliott
1 min readFeb 11, 2024

It looks like some distributions, namely alpine, have adopted PEP 668 which wants to prevent you from mix-and-matching system package manager installed packages with pip installed ones:

A long-standing practical problem for Python users has been conflicts between OS package managers and Python-specific package management tools like pip. These conflicts include both Python-level API incompatibilities and conflicts over file ownership.

This makes sense, but not necessarily for the tiny Dockerfile you’re trying to build for your homelab. So, if you’re getting the following error:

× This environment is externally managed
╰─>
The system-wide python installation should be maintained using the system package manager (apk) only.

If the package in question is not packaged already (and hence installable via “apk add py3-somepackage”), please consider installing it inside a virtual environment, e.g.:

python3 -m venv /path/to/venv

. /path/to/venv/bin/activate

pip install mypackage

Just add this first line to remove the “externally managed” tag to your pip3 install RUN block:

RUN rm /usr/lib/python*/EXTERNALLY-MANAGED && \
python3 -m ensurepip && \
pip3 install <packages>

--

--

Elliott

Personal interests in literature, SF, and whisky/whiskey/scotch, Software Engineer by Trade