python sys.path ModuleNotFoundError: No module named 'file_name' when importing in Docker container

638 Views Asked by At

I am attempting to run a Docker container, but I am encountering the error "ModuleNotFoundError: No module named 'basic_config'" when trying to import the module "basic_config" from the config directory. Although the code runs without any issues on Windows and Linux servers, the error only occurs when running the code inside a base Docker container. I am seeking a solution to resolve this issue and be able to import the module correctly within the Docker container.

this is the file structure

"""
    ml-project/
        enviroment/
            env.dev
            env.prod
        src/
            config/
                base_config.py
            model/
                model1/
                    model.py
            .env
        piplines.yml
        requirements.txt
    """

this this model.py

import sys
sys.path.append("../../config")
from basic_config import AGE

print(AGE)

this is the docker file

FROM python:3.8
WORKDIR /app
COPY . .
ARG env_type=dev
RUN pip install -r requirements.txt
CMD ["python", "src/module/model1/model.py"]
1

There are 1 best solutions below

0
Yasiru Ayeshmantha On

I change the working directory to the module's directory before executing the Python script and it works. Here's the updated Dockerfile

FROM python:3.8
WORKDIR /app
COPY . .
ARG env_type=dev
RUN pip install -r requirements.txt
WORKDIR /app/src/module/model1
CMD ["python", "model.py"]