TheDruidsKeeper
TheDruidsKeeper

Reputation: 325

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?

Upvotes: 3

Views: 1858

Answers (2)

Itamar Turner-Trauring
Itamar Turner-Trauring

Reputation: 3890

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/

Upvotes: 3

Sagar Patil
Sagar Patil

Reputation: 521

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.

Upvotes: 0

Related Questions