Search code examples
dockerdocker-composedocker-swarm

Mounting a host directory to a docker container from yaml/compose file


I have part of my current config like this

mymicroservice:
  image: service_img
  networks: myoverlay
  volumes:
    - /Users/abcdUser/mountme:/opt/company/

This does the job as my machine's directory gets mounted to /opt/company when I deploy the docker swarm service stack.

However, I want to specify the source directory under a separate volumes: and then specify that name over there. I think this is possible but I am not able to find the syntax.

So I want something along the following lines but not able to do so:

mymicroservice:
  image: service_img
  networks: myoverlay
  volumes:
    - myownvolume:/opt/company/


volumes:
 - myownvolume: /Users/abcdUser/mountme

I want to clarify that myownvolume here is just pointing to the directory /Users/abcdUser/mountme and I am not intending to create a docker volume. Or there is any other better way to do this?


Solution

  • It is possible to do so but not with the standard setup. The default volume driver doesn't allow the format you are looking for. You need to use docker plugins which requires external installation. Consider the below yaml

    version: '2'
    
    services:
      one:
        image: alpine
        working_dir: /one/
        command: sleep 600
        volumes:
          - data:/one/
    
      two:
        image: alpine
        working_dir: /two/
        command: sleep 600
        volumes:
          - data:/two/
    
    volumes:
      data:
        driver: local-persist
        driver_opts:
          mountpoint: /data/local-persist/data
    

    Above would work when you have the local-persist plugin installed. https://github.com/CWSpear/local-persist

    You can find about other plugins available on

    https://docs.docker.com/engine/extend/legacy_plugins/#volume-plugins

    Also if repetition of volumes entries is an issues for you then you can use anchors in YAML

    version: '3'
    
    services:
      alpines:
        image: alpine
        command: sleep 200
        volumes: &common_volumes
          - ./data:/data
          - ./config:/config
      alpine2:
        image: alpine
        command: sleep 200
        volumes: *common_volumes
    
    $ docker-compose config
    services:
      alpine2:
        command: sleep 200
        image: alpine
        volumes:
        - /home/vagrant/so/volumes2/data:/data:rw
        - /home/vagrant/so/volumes2/config:/config:rw
      alpines:
        command: sleep 200
        image: alpine
        volumes:
        - /home/vagrant/so/volumes2/data:/data:rw
        - /home/vagrant/so/volumes2/config:/config:rw
    version: '3.0'