I have a functionality which is implemented using Python and Docker.
When I run docker-compose up -d, I am able to build image successfully and also the entire folder is copied into the Docker container and I am able to see the copied files in the container.
But, while running the Python file, I am getting the error
ModuleNotFoundError: No module named "bank_transactions"
In file main_transactions.py, I have imported the constants file, I have shown the folder structure in the screenshot below.

When I run the app through PyCharm, it's working perfectly without any issue.
Below are the Docker file configs.
docker-compose.yml
version: "3.6"
services:
app :
build: .
db:
image: postgres
restart: always
environment:
POSTGRES_USERNAME: root
POSTGRES_PASSWORD: root
POSTGRES_DB: testdb
ports:
- 5432:5432
Dockerfile
FROM python:3.6
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
RUN mkdir /code
WORKDIR /code
COPY . /code/
RUN pip install -r requirements.txt
CMD [ "python", "/Transactions/bank_transactions/main_transactions.py" ]
Error logs:
Traceback (most recent call last):
app6_1 | File "/code/bank_transactions/main_transactions.py", line 5, in <module>
app6_1 | from bank_transactions import constants
app6_1 | ModuleNotFoundError: No module named 'bank_transactions'
At first sight, the error you obtain in the logs
[…] Traceback (most recent call last):
app6_1 | File "/code/bank_transactions/main_transactions.py", line 5, in<module>
app6_1 | from bank_transactions import constants
app6_1 | ModuleNotFoundError: No module named 'bank_transactions'
suggests the file main_transactions.py is indeed parsed, which in turn imports the constants.py file, which fails.
Actually, this is related to the way import walks directories to find python packages and I'm pretty sure your error should vanish by setting the PYTHONPATH environment variable:
FROM python:3.6
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
WORKDIR /code
COPY . /code/
RUN pip install -r requirements.txt
ENV PYTHONPATH /code
CMD [ "python", "/code/bank_transactions/main_transactions.py" ]
For additional details, see this other StackOverflow question (which dealt with Python2 − cf. the ImportError instead of ModuleNotFoundError with Python3 − but the fix should be the same).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With