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

Solution 1:

Add the following lines to your Dockerfile:

RUN apt-get update
RUN apt-get install ffmpeg libsm6 libxext6  -y

These commands install the cv2 dependencies that are normally present on the local machine, but might be missing in your Docker container causing the issue.

Solution 2:

This is a little bit better solution in my opinion. Package python3-opencv includes all system dependencies of OpenCV.

RUN apt-get update && apt-get install -y python3-opencv
RUN pip install opencv-python

Solution 3:

Even though the above solutions work. But their package sizes are quite big. libGL.so.1 is provided by package libgl1. So the following code is sufficient.

apt-get update && apt-get install libgl1

Solution 4:

Try installing opencv-python-headless python dependency instead of opencv-python. That includes a precompiled binary wheel with no external dependencies (other than numpy), and is intended for headless environments like Docker. This saved almost 700mb in my docker image compared with using the python3-opencv Debian package (with all its dependencies).

The package documentation discusses this and the related (more expansive) opencv-contrib-python-headless pypi package.

Example reproducing the ImportError in the question

# docker run -it python:3.9-slim bash -c "pip -q install opencv-python; python -c 'import cv2'"
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/local/lib/python3.9/site-packages/cv2/__init__.py", line 5, in <module>
    from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
# docker run -it python:3.9-slim bash -c "pip -q install opencv-python-headless; python -c 'import cv2'"
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv