Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ModuleNotFoundError and import errors in Docker container

When importing python modules locally, I am able to successfully do so, however I'm having difficulty doing so when dockerising the app. It seems as though I get the opposite behaviour locally to how I get in the docker app... any thoughts?

I have the following directory structure

| app
|      |api.py
|      |settings.py
| tests
|      |test_api.py

In api.py, I import settings by: from app import settings In test_api.py I import app.py by: from app import api.

Locally, everything works fine. When I try to dockerize this API using the following Dockerfile:

FROM python:3.8.5-alpine

RUN pip install pipenv
COPY Pipfile /usr/src/
WORKDIR /usr/src
RUN pipenv lock --requirements > requirements.txt
RUN pip install -r requirements.txt

COPY app /usr/src/app

WORKDIR /usr/src/app

CMD ["python", "api.py"]

The docker image builds successfully, however upon running the container, I get the following error:

File "api.py", line 4, in <module>
from app import settings
ModuleNotFoundError: No module named 'app'

If I change how I import in api.py, to import settings, I get errors locally, but the docker container works perfectly. I'm pretty sure it's something to do with the PythonPath, any thoughts on how I can resolve this?

like image 639
Anish Patel Avatar asked May 22 '26 03:05

Anish Patel


1 Answers

I've just come across another thread on StackOverflow which seems to have resolved my issue. I can leave the import statements as I indicated above in my question, and by setting the PYTHONPATH in the docker container correctly, I am able to get the imports working correctly in docker.

How do you add a path to PYTHONPATH in a Dockerfile

My updated (working) Dockerfile is as follows:

FROM python:3.8.5-alpine

RUN pip install pipenv
COPY Pipfile /usr/src/
WORKDIR /usr/src
RUN pipenv lock --requirements > requirements.txt
RUN pip install -r requirements.txt

COPY app /usr/src/app

ENV PYTHONPATH "${PYTHONPATH}:/usr/src/app"

CMD ["python", "app/api.py"]
like image 118
Anish Patel Avatar answered May 23 '26 15:05

Anish Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!