Here is the directory structure of my project:Directory tree
From the backend folder, I want to create a Docker image that loads the setup.py
and requirements.txt
files which are in the parent folder. Additionally, I want to load the src/
folder which is also in the parent folder. Here is the content of setup.py
: https://github.com/ahmedaao/design-autonomous-car/blob/master/setup.py
and here is the content of fastapi_app.py
: https://github.com/ahmedaao/design-autonomous-car/blob/master/backend_app.py
Here is Dockerfile
:
FROM python:3.10.12
WORKDIR /app
COPY ./fastapi_app.py /app/
COPY ./../requirements.txt /app/
COPY ./../src/ /app/src
COPY ./../setup.py /app/
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD ["uvicorn", "fastapi_app:app", "--host", "0.0.0.0", "--port", "8000"]
When I try to build the image with: sudo docker build -t test .
I have this output: Output from docker build
Maybe you can help to solve this problem. Thanks
You can view the Dockerfile
I tested above.
Your docker build
command is run from the backend/
directory. It might make more sense to run it from the project root.
If your project is structured like this (from your screenshot):
├── backend
│ ├── Dockerfile
│ └── fastapi_app.py
├── requirements.txt
├── setup.py
└── src
├── __init__.py
└── metrics.py
Then perhaps it might make more sense to formulate your Dockerfile
like this:
FROM python:3.10.12
WORKDIR /app
COPY backend/fastapi_app.py /app/
COPY requirements.txt /app/
COPY src/ /app/src
COPY setup.py /app/
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8000
CMD ["uvicorn", "fastapi_app:app", "--host", "0.0.0.0", "--port", "8000"]
You would then build the image from the project root:
docker build -f backend/Dockerfile -t test .
This would be a good approach if you are going to have multiple Dockerfile
in the project (perhaps you will have a frontend/Dockerfile
as well?).
Alternatively, if there will just be a single image, you could move the Dockerfile
to the project root and then your build command would simplify to:
docker build -t test .
Either approach will get you around the problem of trying to copy files from outside of the build context.
Update
In response to question in comments and looking at https://github.com/ahmedaao/design-autonomous-car.
You can reduce the size of the image by adding a specific requirements.txt
into the backend/
folder. Something like this should do it:
uvicorn==0.29.0
numpy==1.26.4
fastapi==0.110.1
pillow==10.2.0
python-dotenv==1.0.1
tensorflow==2.15.0.post1
Then update your Dockerfile
with:
COPY backend/requirements.txt /app/
The resulting image would then be around 2.67 GB. Unfortunately it's the tensorflow
package that's bloating the image. Without that the size drops to 1.11 GB.