Search code examples
dockerdocker-composedockerfilevolumedocker-volume

How do I access a mounted voume from docker-compose in my Dockerfile?


I'm using Docker 19. I have this in my docker-compose.yml file. I'm trying to mount a volume from my local machine ...

  python:
    build: ./
    env_file: /Users/davea/Documents/workspace/my_python_project/tests/.test_env
    environment:
      - ACCEPT_EULA=Y
      - SA_PASSWORD=${LOCAL_DB_PASSWORD}
      - DB_HOST=sql-server-db
      - DB_NAME=${LOCAL_DB_DB}
      - DB_USER=${LOCAL_DB_USERNAME}
      - DB_PASS=${LOCAL_DB_PASSWORD}
      - DB_PORT=1433
    volumes:
    - /Users/davea/Documents/workspace/my_python_project:/my-app
    depends_on:
      - sql-server-db

How do I reference this volume in my Dockerfile? I tried this

WORKDIR /my-app
...
RUN pip3 install -r /my-app/requirements.txt

but am getting this error

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

I have verified that "/Users/davea/Documents/workspace/my_python_project/requirements.txt" is a valid file on my system.


Solution

  • You don't. Volumes are intended to hold data, not code; you should COPY your code into your image and delete the volumes: line.

    A very routine minimal Python Dockerfile can look like:

    FROM python:3.8
    WORKDIR /my-app
    COPY . ./
    RUN pip3 install -r requirements.txt
    CMD ["./my-app.py"]
    

    Since the COPY line is there, the image contains everything it needs to run itself, including its own code and a default command. That means it's available at build time, and it means you can delete the volumes: block from your docker-compose.yml file.

    Many of the things you can specify in the docker-compose.yml just aren't visible or accessible at build time. This includes volumes, networks, and environment variable settings; your build can't connect to other containers.