Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing python files in Docker container

When running my docker image, I get an import error:

File "./app/main.py", line 8, in <module>
import wekinator
ModuleNotFoundError: No module named 'wekinator'`

How do I import local python modules in Docker? Wouldn't the COPY command copy the entire "app" folder (including both files), hence preserving the correct import location?

.
├── Dockerfile
├── README.md
└── app
    ├── main.py
    └── wekinator.py
FROM python:3.7

RUN pip install fastapi uvicorn python-osc

EXPOSE 80

COPY ./app /app

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
like image 401
msalla Avatar asked Jul 17 '26 08:07

msalla


2 Answers

After much confusion, I got the container to run by setting a PYTHONPATH env variable in the Dockerfile:

ENV PYTHONPATH "${PYTHONPATH}:/app/"
like image 111
msalla Avatar answered Jul 19 '26 22:07

msalla


Setting the PYTHONPATH as such works but feels clumsy:

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

Using Docker's WORKDIR allows for a much cleaner solution:

FROM python:3.7

WORKDIR /code

RUN pip install fastapi uvicorn python-osc

EXPOSE 80

COPY app ./app

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]

Note how the COPY statement changed.

like image 25
Sylver11 Avatar answered Jul 19 '26 23:07

Sylver11