This is something that has been bothering me for a while, and the common wisdom I've heard is that it's just not how docker-compose works. I wanted to define bind mounts in my docker-compose.yml so that the volume was described once and could be mounted in multiple containers. Creating named volumes in Compose is well documented, and used to do things like keeping consistent data across multiple container iterations, or share data between containers. What is not well documented, however, is describing a directory on the host system which should be named and mounted to multiple containers. I think that in large-scale applications this is probably uncommon, but for my personal small applications, it's something I use all the time.

Here is an example of how someone might create a docker-compose.yml that hosts a small PHP application with nginx and redis, where php and nginx both need access to a content/data directory.

version: '3.5'
services:
  php:
    image: php:fpm-alpine
    volumes:
      - /home/chasevasic/webapp/data:/var/www/
  nginx:
    image: nginx:alpine
    volumes:
      - /home/chasevasic/webapp/data:/var/www/
   redis:
     image: redis

This is fine, but it can get irritating as time goes on to be referencing an absolute path on the Docker host multiple times. I knew there had to be a better way, even if it wasn't well documented. After some fiddling around and making assumptions based on what is documented, I found a way to describe a named volume which is a bind mount.

version: '3.5'
services:
  php:
    image: php:fpm-alpine
    volumes:
      - content:/var/www
  nginx:
    image: nginx:alpine
    volumes:
      - content:/var/www
   redis:
     image: redis
volumes:
  content:
    driver: local
    driver_opts:
      o: bind
      device: /home/chasevasic/webapp/data

Maybe this is just OCD thinking, but I think it's much better to define the host path just once. I couldn't find any examples of people doing this online. This solution could also make sense for ssh or nfs volumes, not just bind mounts.