Search code examples
dockerdocker-composedockerfiledocker-volume

mount files present in a directory in docker image with the directory in the host


I have a docker image in which there are few configuration files present in the directory /opt/app/config now i wanted to mount this directory to a host directory so that config files can be accessed from host.

my docker compose is a follows

  web:
    image: web:v1
    container_name: web
    volumes:
      - ./config:/opt/app/config
    command: ["tail","-f","/dev/null"]
    ports:
      - 5000:5000

if i run the individual web image using docker run -it web:v1 bash and do ls /opt/app/config i can see the config files

but using docker-compose upthe containers are getting created but the files are not being reflected in the host path.

when i do ls ./config the directory is empty. The expected behaviour is the files present in docker image at /opt/app/config shloud be reflected in my host ./config directory.


Solution

  • When you mount a host directory into container, the contents of host directory shadow the contents of container.

    If you want to access files present in container on host, you can mount a named volume as follows.

    services:
      web:
        image: web:v1
        container_name: web
        volumes:
          - config:/opt/app/config
        command: ["tail","-f","/dev/null"]
        ports:
          - 5000:5000
    volumes:
      config:
    

    Then you can find the path of config volume using docker inspect config and see the contents from the container.

    If you want to specify the path on host machine, you can specify the path of named volume in compose file as follows.

    volumes:
      config:
        driver_opts:
          o: bind
          device: /tmp/2    ------> Path on host machine