Specifying top-level and service-level volumes in compose file

Hello!

I am using a compose file to create and run an application with two services: mariadb and keycloak

I would like to use a top-level mount for this multi-container application, say /avolume/forthisapplication/

This volume has two sub-directories for the individual services like:

/avolume/forthisapplication/mariadb/
/avolume/forthisapplication/keycloak/

I would like to provide each service its corresponding subdirectory as a volume

What should the syntax of the compose file be? I tried the following but get the error “service refers to undefined volume”:

services:
  thisapp_db:
    image: mariadb
    volumes:
      - type: volume
        source: forthisapplication_data/mariadb/mysql
        target: /var/lib/mysql:Z

volumes:
  forthisapplication_data:
    driver: local
    driver_opts:
      device: /avolume/forthisapplication/
      type: local
      o: bind

Many thanks!

Since docker > =26.0 volumes started to support volume subpaths:
https://docs.docker.com/compose/compose-file/05-services/#long-syntax-5

I am on 26.1.0, but couldn’t make it work with bind backed volumes. The syntax should look like this:

services:
  thisapp_db:
    image: mariadb
    volumes:
      - type: volume
        source: forthisapplication_data
        volume:
          subpath: mariadb/mysql
        target: /var/lib/mysql:Z

Note: I am not sure, if volume subpaths actually work on a bind backed volume, and whether appending the access mode “:Z” actually works with the long syntax. I know it’s supported if type: bind and selinux: Z is used in the volumes bind property…

Update: I tried it now with a named volume backed by an nfsv4 remote share → works like a charm. Though, I still can’t get it working with a named volume backed by a bind.

1 Like

Thanks so much for your help! I will try it with bin and let you know.

For now I have taken the simplest approach and just created individual mounts for the services. Not my most favorite approach but in a bit of a rush.

Thanks so much again!