How to create a host mount path in compose file top-level volumes key

In a compose file, how can I create a volume that is bound to some host path,
using the top-level volumes key?

Basically, I have this:

services:
  foo:
    volumes:
      - type: bind
        source: /host/path
        target: /container/path

And I want to turn it into this:

services:
  foo:
    volumes:
     - type: volume
       source: host-path
       target: /container/path

volumes:
  host-path:
    driver: ???
    driver_opts: ???

The documentation for the volumes service key states:

If the mount is a host path and is only used by a single service,
it MAY be declared as part of the service definition
instead of the top-level volumes key.

To reuse a volume across multiple services,
a named volume MUST be declared in the top-level volumes key.

Which implies the top-level volumes key supports creating a bind volume.

However, the top-level volumes key documentation doesn’t say anything
about this. It merely states:

Default and available [driver] values are platform specific.

And searching a bit, I couldn’t find which drivers are available for my
platform. Even less how to configure them.

You can create a volume backed by a bind like this:

volumes: 
  host-path:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: /host/path

Docker only ships with the local driver. Even though the driver is called local, it does not say anything about what can be mounted with it, it just says that it is locally managed on the node. The local driver can mount nfs and cifs remote shares, or bind local folders.

Note: volume configurations are immutable! Once created, changes to the volume configuration in the compose file will not be reflected back to the volume configuration. In order to apply changes, the existing volume must be deleted, so that compose can re-create the volume with the new values.

2 Likes

Thank-you very much!