python-3.xdockerdockerfilepython-module

Docker python not able to recognize custom module


I have a project with the following structure:

project/
  checks/
    __init__.py
    <some files here>

  engine/
    __init__.py
    <some files here>

  models/
    __init__.py
    <some files here>

  __init__.py
  logger.py
  main.py
  requirements.txt
  Dockerfile

main.py looks something like this:

from project.logger import log

if __name__ == '__main__':
  <code>

If I run main.py, in my editor (PyCharm 2024.3), everything works fine. However, if I put everything in Docker, I get:

Traceback (most recent call last):
  File "/project/main.py", line 3, in <module>
    from project.logger import log
ModuleNotFoundError: No module named 'project'

My Dockerfile looks like this:

FROM python:3.13-alpine
WORKDIR /project
COPY ./requirements.txt /project/requirements.txt
RUN python -m pip install --no-cache-dir --upgrade pip
RUN pip install --no-cache-dir --upgrade -r /project/requirements.txt

COPY ./checks /project/checks
COPY ./engine /project/engine
COPY ./models /project/models

COPY ./__init__.py /project/__init__.py
COPY ./logger.py /project/logger.py
COPY ./main.py /project/main.py

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

Am I doing something wrong? Is there a way to force Python to recognize the module?


Solution

  • Am I doing something wrong?

    Yes. If you try to import project, there needs to be either a file named project.py or a directory named project (that contains file __init__.py) somewhere in Python's search path (which includes the directory containing your script and standard locations like /usr/lib/python).

    Since you are running your code from inside the project directory, the directory itself is effectively invisible to Python.

    Instead of:

    from project.logger import log
    

    Write instead:

    from logger import log
    

    Python will find logger.py in the current directory and work as expected.

    You can also dramatically simplify your Dockerfile:

    FROM python:3.13-alpine
    
    WORKDIR /project
    
    # Install dependencies
    COPY ./requirements.txt ./
    RUN python -m pip install --no-cache-dir --upgrade pip && \
      pip install --no-cache-dir --upgrade -r requirements.txt
    
    # Install application code
    COPY . ./
    
    CMD ["python", "main.py"]