3

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?

TheDruidsKeeper
  • 325
  • 3
  • 12

2 Answers2

2

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/

Itamar Turner-Trauring
  • 3,430
  • 1
  • 13
  • 17
  • Looking in `/usr/local/lib` it actually appears there are 3 versions that come with the image (2.7, 3.7, & 3.8). Running `which python3` does show that it's using the binary `/usr/local/bin/python3`, which is a symlink to `python3.8`. It still doesn't make sense to me why it wouldn't be able to import the NumPy module? It seems like all recommendations point to using pip to install dependencies rather that installing the packages from apt - if so, why does apt even have these packages? – TheDruidsKeeper Jul 06 '20 at 20:28
  • Alternative solution is to use python from the package repositories with a debian base image. – SuperSandro2000 Jul 07 '20 at 07:53
  • The issue is that the base image is Debian + its own Python. So from Debian's perspective it makes sense to have its own NumPy so you can install Debian packages that depend on it. From Docker image perspective, this doesn't make sense. – Itamar Turner-Trauring Jul 07 '20 at 15:46
0

The problem is with python environments, not with docker. The apt-get installed numpy is not in the same environment as the python installation. Moreover, the dependencies should be stored in a requirements.txt file, which should then be installed through pip. python -m pip can be used to ensure that the pip command is in the same environment as the python installation.

Sagar Patil
  • 507
  • 2
  • 7
  • 18