Share a named volume among several services

First of all here is my scenario

+ tree
├── 1.yml
└── 2.yml

+ cat 1.yml
services:
    service1:
        image: bash
        volumes:
            - dir:/dir
volumes:
    dir:

+ cat 2.yml
services:
    service2:
        extends:
            file: 1.yml
            service: service1
        volumes:
            - dir:/dir

To notice

        extends:
            file: 1.yml
            service: service1

Now a little attention

+ docker compose -f 2.yml run --rm service2 ls -dl /dir
service "service2" refers to undefined volume dir: invalid compose project
+ docker compose -f 1.yml run --rm service1 ls -dl /dir
drwxr-xr-x    2 root     root          4096 Jul 26 08:22 /dir

As you can see, if I use service2, there is any problem.
While if I use service1… everything is ok.

Why?

You need to define a volumes: section in every compose file (doc).

Make sure to set a name:, as compose usually prefixes volumes per compose file.

1 Like

If I am not mistaken, the prefixes to container and volume names are based on the COMPOSE_PROJECT_NAME, and not the compose file name

The project name defaults to the name of the directory the compose files are in

@bluepuma77

1 Like

But if the section is particularly nourished

volumes:
    dir:
    dir2:
    dir3:
    dir4:
    dir5:
    dir6:
    dir7:
    ...

replicating it on each file I see it a too uncomfortable thing.
And if for example after a month I have to make a change, I have to remember to replicate it on each compose file: which is impossible, because I would not be able to remember the names of each individual compose file.

Why not simply place all services in the same compose file?

Alternatively you should be able to use a common base and then an extra service file on top.

docker compose -f docker-compose.base.yml -f docker-compose.override.yml up
1 Like