docker-compose.yml Syntax for Named Volumes

Petrus Theron picture Petrus Theron · Oct 15, 2018 · Viewed 10.5k times · Source

What is the docker-compose.yml syntax for specifying the host path of a named volume?

docker-compose.yml:

volumes:
  myvolume:  # how do I specify path here?
  othervolume:

services: # etc...

I've checked the docs, but I can't find it. Honestly, I don't know how anyone uses this stuff.

Answer

BMitch picture BMitch · Oct 15, 2018

The common scenario with compose volumes is to use the default named volume which maps to the local volume driver and places volumes in /var/lib/docker/volumes. Not what you're looking for, but this is the easy option for many:

version: '3'
volumes:
  myvolume:
  othervolume:    
services:
  myservice:
    volumes:
      - myvolume:/volume/path

The common method to map a host volume is to specify the path directly, no name needed on the volume. Again, not what you're asking for, but it's very easy to implement. This is a bind mount under the covers:

version: '3'
services:
  myservice:
    volumes:
      - ./path:/volume/path

If you want a named volume and host volume together, what you're looking for is a named volume configured to use a bind mount. This has the downside of failing if the directory does not preexist, but has the upside that docker can init an empty directory to the contents of the image.

version: '3'
volumes:
  myvolume:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: /host/path/to/volume
services:
  myservice:
    volumes:
      - myvolume:/container/volume/path

Note, the downside of bind mounts is that it places files that are managed by containers, with the uid/gid from the container, inside a path likely used by other users on the host, often with a different uid/gid on the host. The result is permission issues either on the host or inside the container. You need to align uid/gid's between the two to avoid this.