How to inherit/merge volumes from yaml anchors in docker-compose?

Viewed 143

I want my docker-compose file to merge (reuse) volumes definitions, as follows:

x-defaults: &my-defaults:
  volumes:
    - /first:/volume
    - /second:/volume

services:  
  my-service1:
    <<: *my-defaults
    volumes:
      - /additional:/volume
 
  my-service2:
    <<: *my-defaults
    volumes:
      - /custom:/vol

Result: only the /additional:/volume is mapped.

Question: how can I achieve a real merge here?

2 Answers

Simple answer: it's not possible. Array lists are replaced on inheritance, thus when overriding, have to repeat all list statements.

The simple workaround could be to define a nested YAML anchor like this:

x-defaults: &my-defaults:
  volumes: &my-volumes
    - /first:/volume
    - /second:/volume
    
services:  
  my-service1:
    <<: *my-defaults
    volumes:
      <<: *my-volumes
      - /additional:/volume
     
  my-service2:
    <<: *my-defaults
    volumes:
      <<: *my-volumes
      - /custom:/vol
Related