Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run python file in subdirectory Docker

I have the following file structure

project 
├── app
│   ├── main.py
│   └── combine.py
│   └── scrape.py
├── resources
|    └── secrets.py
|    └── config.py
|    └── requirements.txt
|--- Dockerfile

My Dockerfile looks like

FROM python:3.8
RUN mkdir /project
WORKDIR /project

COPY ./resources/requirements.txt ./
ADD ./resources/. /resources/
ADD ./app/. /app/

RUN pip install -r ./requirements.txt

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

I build my image using docker build -t my-app . and run using docker run my-app

I get the following error python: can't open file './app/main.py': [Errno 2] No such file or directory

Can I keep subdirectory file structure and successfully run a Docker image? All the tutorials/ questions I have seen previously have the Dockerfile in the same directory as all the code that it depends on - is this a requirement? Thanks in advance!

like image 885
greenPlant Avatar asked Sep 03 '25 10:09

greenPlant


1 Answers

Your WORKDIR is set to /project.

Your CMD is run as './app', so that translates to '/project/app'.

You're copying app to '/app', so use this:

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

like image 77
Oli Avatar answered Sep 04 '25 23:09

Oli