'Docker build cannot install python requirements from file if python project is mounted in docker-compose

I have a python image I run from docker-compose.yml. I mount the python code as a volume so I do not need to rebuild the container with every code change:

docker-compose.yml

services:
  python:
    container_name: py
    build: .
    volumes:
      - ./app:/usr/src/app
    env_file:
      - .env
    working_dir: /usr/src/app
    command: python ./core/main.py

Where build: . is refering to the Dockerfile in the same directory.

The app/ which is the python root directory, contains standard requirements.txt. The problem is I cannot install the dependencies in requirements.txt during docker build using RUN pip install -r requirements.txt in Dockerfile since the volume is not yet mounted.

I can't seem to solve this which makes me think I am not practicing the best usage of docker/docker-compose.

How can I solve this?

Dockerfile

FROM python:3.7.12-slim-bullseye
RUN mkdir /usr/src/app
WORKDIR /usr/src/app
RUN pip install -r requirements.txt
ENV PYTHONBUFFERED 1

As expeceted, running docker compose build py causes:

ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' 


Solution 1:[1]

instead of doing this on docker-compose:

volumes:
      - ./app:/usr/src/app

I usually use this other approach in Dockerfile:

WORKDIR /usr/src/app #if folder doesn't exist this will be created, so you can omit RUN mkdir /usr/src/app
COPY ./app/requirements.txt /usr/src/app
RUN pip install -r requirements.txt

COPY ./app /usr/src/app

if you are using a virtual folder inside you will need a .dockerignore file to avoid that space consumption in the container

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dullich