ImportError: libGL.so.1: cannot open shared object file in a container
The OpenCV wheel links the GUI stack. Install the runtime libraries, or use the headless wheel that removes the dependency altogether.

Introduction & Quick Summary
ImportError: libGL.so.1: cannot open shared object file: No such file or directoryimport cv2 fails because the wheel loads a shared library that is not installed. opencv-python is built with GUI support, so it links against OpenGL and related X libraries; a slim container image has none of them, and the dynamic loader stops at the first missing one.
The library that fails is not always libGL.so.1; the same cause produces a series of similar errors as each missing dependency is installed:
libGL.so.1from the OpenGL client library used byhighgui, even when no window is ever opened.libglib2.0-0, which provideslibgthread-2.0.so.0and is a dependency of the video stack.libSM.so.6andlibXext.so.6for the X session and extension library.libgomp.so.1, which OpenCV's parallel backend needs and which is missing from some distroless and Alpine variants.
| Missing library | Package (Debian/Ubuntu) | Package (Alpine) | Needed when |
|---|---|---|---|
libGL.so.1 | libgl1 | mesa-gl | opencv-python on a headless server |
libglib-2.0.so.0 | libglib2.0-0 | glib | Video and some image codecs |
libSM.so.6 | libsm6 | libsm | X session handling |
libXext.so.6 | libxext6 | libxext | X extensions |
libgomp.so.1 | libgomp1 | libgomp | Parallel cv2 operations |
Core Mechanics, Signatures & Reproducible Setup
A Python wheel on Linux is not self-contained: it bundles OpenCV's own shared objects but not the system libraries those link against. The dynamic loader resolves them at import time, in the order the ELF headers list them, and raises ImportError for the first one it cannot find. That is why the error message changes to the next library after each apt-get install.
A reproduction is a clean slim image:
FROM python:3.13-slim
RUN pip install --no-cache-dir opencv-python==4.12.0.88
RUN python -c "import cv2; print(cv2.__version__)"ImportError: libGL.so.1: cannot open shared object file: No such file or directory# inspect what the extension actually needs
python - <<'PY'
import cv2, subprocess, sys
print(cv2.__file__)
PY
ldd $(python -c "import cv2,os;print(os.path.join(os.path.dirname(cv2.__file__),'cv2.abi3.so'))") | grep "not found"The ldd output lists every unresolved dependency at once, which is faster than installing one package per error.
Key Comparison Table
The correct fix is often a different package rather than more system libraries, because a server does not need the GUI stack at all.
| Package | GUI functions | libGL required | Size overhead | Use case |
|---|---|---|---|---|
opencv-python | imshow, waitKey, trackbars | Yes | Large | Desktop or debugging with a display |
opencv-python-headless | Stubs only | No | Small | Servers, containers, CI |
opencv-contrib-python | Yes, plus contrib modules | Yes | Largest | SIFT, tracking, extra algorithms |
opencv-contrib-python-headless | Stubs, plus contrib modules | No | Large | Servers needing contrib |
Distribution python3-opencv | Yes | Yes, declared | n/a | System Python on Debian |
The headless and regular variants cannot be installed side by side, because they ship the same cv2 module. Pick one and pin it.
| Constraint | opencv-python | opencv-python-headless |
|---|---|---|
| Runs on a slim base image without apt packages | No | Yes |
cv2.imshow | Works | Raises an error |
cv2.VideoCapture on a file | Works | Works |
cv2.VideoCapture from a GUI backend | Works | Not available |
Works with matplotlib, Pillow, web uploads | Yes | Yes |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Install the minimal runtime libraries
When the regular package is required, install the runtime libraries only, without the compiler toolchain. On current Debian the OpenGL package is libgl1; the older libgl1-mesa-glx name is a transitional package.
FROM python:3.13-slim
RUN apt-get update && apt-get install -y --no-install-recommends \
libgl1 libglib2.0-0 libsm6 libxext6 libgomp1 \
&& rm -rf /var/lib/apt/lists/*
RUN pip install --no-cache-dir opencv-python==4.12.0.88docker run --rm img python -c "import cv2; print(cv2.__version__, cv2.getBuildInformation().splitlines()[0])"Installing libgl1 alone fixes libGL.so.1 and then surfaces the next missing library, so install the group in one layer rather than iterating.
Prefer the headless package on servers
opencv-python-headless compiles out the GUI module and the libraries it needs, which removes the problem instead of satisfying it. The import surface for image processing is unchanged.
pip uninstall -y opencv-python opencv-contrib-python
pip install --no-cache-dir opencv-python-headless==4.12.0.88
python -c "import cv2; print(cv2.__version__)"# drawing and encoding do not need a display
import cv2
import numpy as np
image = np.zeros((200, 300, 3), dtype=np.uint8)
cv2.putText(image, "ok", (20, 100), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 255, 255), 3)
ok, buffer = cv2.imencode(".webp", image)
print(ok, len(buffer))cv2.imshow is the only common call that needs the GUI build; a service that writes files or returns encoded bytes never calls it.
Alpine and musl images
Alpine wheels are musllinux, and many projects publish only manylinux. Installing opencv-python on Alpine either builds from source or installs a wheel that cannot load, so the package name and the base image have to agree.
FROM python:3.13-alpine
RUN apk add --no-cache libstdc++ libgcc glib mesa-gl libgomp
RUN pip install --no-cache-dir opencv-python-headless==4.12.0.88# confirm which wheel was installed
pip debug --verbose 2>/dev/null | grep -i musllinux | head -3
pip show opencv-python-headless | grep -E "Version|Location"A manylinux wheel on musl fails at import with a missing interpreter or library, which looks like the same class of error but is not fixable with apk add.
Distroless and scratch images
A distroless base has no package manager, so the libraries must be copied into the final stage. This is the case where ldd output is the only reliable inventory.
FROM python:3.13-slim AS build
RUN apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0 libgomp1
RUN pip install --target /opt/py opencv-python==4.12.0.88
FROM gcr.io/distroless/python3-debian12
COPY /opt/py /opt/py
ENV PYTHONPATH=/opt/pydocker run --rm img python -c "import cv2; print(cv2.__version__)"If a library is still missing, copy it and its transitive dependencies from the build stage and set LD_LIBRARY_PATH, or switch to a headless wheel so the list is short.
Why it works in development and fails in production
A developer machine has a desktop stack installed, so the same requirements.txt imports fine. Reproducing inside the target base image is the only reliable check.
python -c "import cv2; print(cv2.__file__)" # dev machine
docker run --rm -v "$PWD":/app -w /app python:3.13-slim \
sh -c "pip install -q opencv-python==4.12.0.88 && python -c 'import cv2'" # target image# confirm the interpreter and the site-packages path match what production uses
python -c "import sys, cv2; print(sys.executable, cv2.__file__)"A virtualenv created on the host can be mounted into a container, which is another way the same error appears only in one environment.
Other libraries in the same family
Once libGL.so.1 is resolved, the next failures are usually libglib-2.0.so.0 for video decoding and libgomp.so.1 for parallel loops. Each has a package, and each appears only when the code path using it runs.
apt-get install -y --no-install-recommends libglib2.0-0 libgomp1 libsm6 libxext6 libxrender1# list every unresolved dependency of the cv2 extension in one pass
ldd "$(python -c 'import cv2,os;print(os.path.join(os.path.dirname(cv2.__file__),"cv2.abi3.so"))')" \
| grep -i "not found" || echo "all resolved"Common Compilation/Runtime Mistakes & Version Gotchas
Installing libgl1-mesa-glx on a current distribution. The package is transitional or absent on newer releases, and apt-get install fails before Python is ever involved. Use libgl1.
Installing opencv-python and -headless together. Both provide cv2, so the last install wins and the import behaviour depends on install order. Uninstall both before switching.
Adding apt-get install after pip install in a different layer. It works, but the image keeps the apt lists and the build cache is invalidated by unrelated changes. Put system packages before Python packages.
Blaming the Python version. The error is a missing system library, not a wheel incompatibility; a version mismatch produces ImportError: numpy.core.multiarray failed to import or a symbol lookup error instead.
Ignoring the numpy ABI. opencv-python 4.12 requires a recent numpy 2.x; a pinned numpy 1.26 can produce a different import error in the same file, so read the first line of the traceback.
Version notes. opencv-python 4.10 and later publish abi3 wheels, so a single wheel covers Python 3.9 and newer; older wheels were built per version. The headless variant has existed since 4.3. Debian 12 renamed the OpenGL runtime package to libgl1, and Debian 13 continues that. musllinux wheels for OpenCV remain limited, so Alpine usually means apk packages or a glibc base.
Order: run ldd on cv2.abi3.so, install the listed packages, then decide whether the GUI build is needed at all. For a deployment that only returns bytes, the headless wheel removes the whole class of failure, and the env reader confirms which PYTHONPATH and interpreter the container actually runs. When two requirements files disagree, the text diff shows the package that changed.
Official references: opencv-python on PyPI and the opencv-python repository.
Official references
primary documentationThe Python documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesasyncpg DuplicatePreparedStatement on PgBouncer and Supabase
asyncpg caches prepared statements per connection while a transaction pooler rotates connections underneath it. The cache setting, pool sizing and retry that fix it.
Python Tabulate: Markdown Grid Headers and Alignment
Use Python's tabulate library to format Markdown tables, set custom headers, and control column alignment with pipe and grid formats.
Using pytest.mark.parametrize for Parameterized Tests in Python
Learn how to use pytest.mark.parametrize to write parameterized tests in Python. Covers syntax, multiple arguments, fixtures, custom IDs, class/module-level use, and common pitfalls.
Django select_related and prefetch_related: Fix N+1 Queries
Learn how to eliminate N+1 queries in Django with select_related and prefetch_related, including practical examples, when to use each, and common pitfalls.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.