Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readPython
#Python#OpenCV#Docker#Linux
A python import crate blocked by a missing library plug, amber libgl plate and cyan headless wheel crate

Introduction & Quick Summary

text
ImportError: libGL.so.1: cannot open shared object file: No such file or directory

import 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.1 from the OpenGL client library used by highgui, even when no window is ever opened.
  • libglib2.0-0, which provides libgthread-2.0.so.0 and is a dependency of the video stack.
  • libSM.so.6 and libXext.so.6 for 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 libraryPackage (Debian/Ubuntu)Package (Alpine)Needed when
libGL.so.1libgl1mesa-glopencv-python on a headless server
libglib-2.0.so.0libglib2.0-0glibVideo and some image codecs
libSM.so.6libsm6libsmX session handling
libXext.so.6libxext6libxextX extensions
libgomp.so.1libgomp1libgompParallel 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:

dockerfile
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__)"
text
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
bash
# 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.

PackageGUI functionslibGL requiredSize overheadUse case
opencv-pythonimshow, waitKey, trackbarsYesLargeDesktop or debugging with a display
opencv-python-headlessStubs onlyNoSmallServers, containers, CI
opencv-contrib-pythonYes, plus contrib modulesYesLargestSIFT, tracking, extra algorithms
opencv-contrib-python-headlessStubs, plus contrib modulesNoLargeServers needing contrib
Distribution python3-opencvYesYes, declaredn/aSystem 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.

Constraintopencv-pythonopencv-python-headless
Runs on a slim base image without apt packagesNoYes
cv2.imshowWorksRaises an error
cv2.VideoCapture on a fileWorksWorks
cv2.VideoCapture from a GUI backendWorksNot available
Works with matplotlib, Pillow, web uploadsYesYes

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.

dockerfile
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.88
docker 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.

bash
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__)"
python
# 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.

dockerfile
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
bash
# 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.

dockerfile
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 --from=build /opt/py /opt/py ENV PYTHONPATH=/opt/py
docker 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
bash
# 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.

bash
apt-get install -y --no-install-recommends libglib2.0-0 libgomp1 libsm6 libxext6 libxrender1
bash
# 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 documentation

The Python documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.