How to mount a host directory with docker-compose, with the "~/path/on/host" to be specified when running the host, not in the docker-compose file

11,111
version: '3'

services:
  my-app:
    build:
      context: .
      dockerfile: ./path/to/Dockerfile
    volumes:
      - ~/path/on/host:/path/on/container
    ports:
      - "3000:3000"

Then you can start your service with docker-compose up -d. Make sure to stop and remove first the container you started using docker commands otherwise you will get conflicts.

EDIT BASED ON COMMENT:

Create a .env file with the contents:

HOST_PATH=~/path/on/host

and change your docker-compose.yml:

version: '3'

services:
  my-app:
    build:
      context: .
      dockerfile: ./path/to/Dockerfile
    volumes:
      - ${HOST_PATH}:/path/on/container
    ports:
      - "3000:3000"
Share:
11,111
Billy Ruth
Author by

Billy Ruth

Updated on June 05, 2022

Comments

  • Billy Ruth
    Billy Ruth almost 2 years

    I'm wondering how you can mount a host directory using docker-compose.

    At the moment I'm just using a regular Dockerfile and it's working fine. When I run the container I just specify the path on my host and the path on the container.

    docker run -d -p 3000:3000 -v ~/path/on/host:/path/on/container my-container
    

    I'd like to to achieve this using docker-compose but I'm not sure how this works.My docker compose is below.

    version: '3'
    
    services:
      my-app:
        build:
          context: .
          dockerfile: ./path/to/Dockerfile
    

    In addition, I need the ~/path/on/host to be specified when running the host, not in the docker-compose file.

  • Billy Ruth
    Billy Ruth almost 5 years
    I want the ~/path/on/host to be specified when running the host, not in the docker-compose file
  • Mihai
    Mihai almost 5 years
    I am not sure what you mean with "when running the host" but I updated the solution with a setting that comes from a variable set on host.
  • Wes
    Wes over 3 years
    This doesn't work for me. The directory is always empty.