Importing python files in Docker container

Viewed 4304

This must be a common question but I can't find a proper answer: 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"]
2 Answers

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

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

You need to see which WORKDIR you’re using on your install.

Seems that you’re trying to execute the script from your workdir but you’re copying the data to your root folder inside your container.

Create your docker, run it and check if the files copied in COPY command are in the right folder.

You can do this running docker compose exec <name of your container> ls and check if the ls command lista the folder that you’re trying to call.

Related