Search code examples
docker-composeyaml

Is it possible to create a variable for volumes in docker-compose and share it across services?


I am trying to achieve something among these lines but it throws an error yaml: map merge requires map or sequence of maps as the value is there a way to achieve something like that?

x-backend: &backend
  image: image:1.0
  build:
    context: ./backend
  restart: always

x-backend-volumes: &backend-volumes
    - ./backend/src:${BACKEND_PATH}
    - ./backend/entry.sh:/usr/local/bin/entry.sh
    - ./frontend/src:${FRONTEND_PATH}

services:
  backend_1:
    <<: *backend
    volumes:
        <<: *backend-volumes
        - ./additional_volume:/additional_volume

volumes:
  frontend_dist_1: {}
  frontend_nuxt_1: {}
  frontend_cache_1: {}
  backend_1_files: {}

Solution

  • The YAML merge key is exclusively for mappings and cannot be used on sequences. There is no similar feature for sequences. You're out of luck on this one.

    Best you can do is to link each item separately:

    x-backend: &backend
      image: image:1.0
      build:
        context: ./backend
      restart: always
    
    x-backend-volumes:
        - &x1 ./backend/src:${BACKEND_PATH}
        - &x2 ./backend/entry.sh:/usr/local/bin/entry.sh
        - &x3 ./frontend/src:${FRONTEND_PATH}
    
    services:
      backend_1:
        <<: *backend
        volumes:
            - *x1
            - *x2
            - *x3
            - ./additional_volume:/additional_volume