简体   繁体   中英

Dockerfile: can't open file './main.py': [Errno 2] No such file or directory

I get this error: python: can't open file '/src/main.py': [Errno 2] No such file or directory when I try to run a container with an image that was build with the following docker file:

FROM python:3.9-slim AS compile

RUN python -m venv /opt/venv

ENV PATH="/opt/venv/bin:$PATH"

WORKDIR /my-app

COPY requirements.txt .
RUN pip install -r requirements.txt

ADD src/ ./src
RUN pip install .

FROM python:3.9-slim AS build

COPY --from=compile/opt/venv /opt/venv

ENV PATH="/opt/venv/bin:$PATH"

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

I tried this as well and it still gives me the same type of error about not finding the main.py: i tried./src/main/py, /src/main.py, /src/main.py, ./main.py. I tried everything, I'm starting to suspect the error is elsewhere

/src/main.py is absolute path from the system root.

In order to be relative to you current directory use ./src/main.py

I would simplify your docker file as below:

    # base image
    FROM amazonlinux:1
    
    # Set the working directory
    WORKDIR /app
    
    # Copy the current directory contents into the container at /app
    COPY . /app
    
    # Install requirements
    RUN pip install -r requirements.txt
    
    # Define environment variable
    ENV PYTHONPATH "${PYTHONPATH}:/app"

    # Run main.py when the container launches
    ENTRYPOINT ["python", "-u", "src/main.py"]

The problem is you have multistaged build (2x FROM) and you only add them to the first stage.


FROM python:3.9-slim AS compile

[..]

ADD src/ ./src
ADD setup.py .
RUN pip install .

FROM python:3.9-slim AS build

[..]

You can fix this with a second COPY --from= statement in the 2. stage. Additionally your CMD is wrong. Either give it the fullpath or start a relative path with a. the dir-/filename ( /my-app/src/main.py , ./src/main.py , src/main.py ).

FROM python:3.9-slim AS compile

RUN python -m venv /opt/venv

ENV PATH="/opt/venv/bin:$PATH"

WORKDIR /my-app

COPY requirements.txt .
RUN pip install -r requirements.txt

ADD src/ ./src
ADD setup.py .
RUN pip install .

FROM python:3.9-slim AS build

COPY --from=compile/opt/venv /opt/venv

COPY --from=compile/my-app /my-app                  # ADDED

WORKDIR /my-app                                     # ADDED

ENV PATH="/opt/venv/bin:$PATH"

CMD ["python", "/my-app/src/main.py"]                      # FIXED

Lastly, you're only setting the workdir in the stage you throw away, but that's only relevant if you don't give the cmd the full path or you need a specific workdir.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM