Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Docker python unable to import module installed via apt-get

I'm trying to build a python app via docker, but it fails to import numpy even though I've installed the appropriate package via apt. As an example of the dockerfile reduced to only what's important here:

FROM python:3

RUN apt-get update \
    && apt-get install python3-numpy -y
RUN python3 -c "import numpy; print(numpy.__version__)"

Attempting to build that dockerfile results in the error ModuleNotFoundError: No module named 'numpy'.

I am able to get this working if I use pip to install numpy, but I was hoping to get it working with the apt-get package instead. Why isn't this working the way I would expect it to?

like image 835
TheDruidsKeeper Avatar asked Oct 23 '25 18:10

TheDruidsKeeper


1 Answers

The problem is that you have two Pythons installed:

  1. The image comes with python in /usr/local/bin.
  2. When you install python3-numpy, that install python3 package from Debian, which ends up with /usr/bin/python.

When you run your code at the end you're likely using the version from /usr/local/bin, but NumPy was installed for the version in /usr/bin.

Solution: Install NumPy using pip, e.g. pip install numpy, instead of using apt.

Long version, with other ways you can get import errors: https://pythonspeed.com/articles/importerror-docker/

like image 94
Itamar Turner-Trauring Avatar answered Oct 26 '25 08:10

Itamar Turner-Trauring