My goal is to recuse duplicated volume definition within each service
I read the following Stackoverflow questions/answers but they did not help:
Current attempts:
Variant 1:
Using default-volumes
with a dash prefix like every array entry has to (relates to the first SO question)
version: '2.4'
x-default-volumes: &default-volumes
- /etc/localtime:/etc/localtime:ro
x-default-service: &default-service
image: my-image-name:my-tag
restart: unless-stopped
volumes:
*default-volumes
networks:
my-network:
services:
service1:
<<: *default-service
image: service1-image:tag
service2:
<<: *default-service
image: service2-image:tag
volumes:
- *default-volumes
- service2:/path/on/container
networks:
my-network:
volumes:
service2: {}
docker-compose config
ERROR: The Compose file './docker-compose.yml' is invalid because: services.service2.volumes contains an invalid type, it should be a string, or an object
Variant 2: An alternative attempt...
version: '2.4'
x-default-volumes: &default-volumes
- /etc/localtime:/etc/localtime:ro
x-default-service: &default-service
image: my-image-name:my-tag
restart: unless-stopped
volumes:
*default-volumes
networks:
my-network:
services:
service1:
<<: *default-service
image: service1-image:tag
service2:
<<: *default-service
image: service2-image:tag
volumes:
*default-volumes
- service2:/path/on/container
networks:
my-network:
volumes:
service2: {}
docker-compose config
ERROR: yaml.parser.ParserError: while parsing a block mapping
in "./docker-compose.yml", line 20, column 5 expected , but found ''
in "./docker-compose.yml", line 24, column 7
Without the usage of the asterisk character in the service2
volumes definition, a docker-compose config
command yields a valid result.
version: '2.4'
x-default-volumes: &default-volumes
- /etc/localtime:/etc/localtime:ro
x-default-service: &default-service
image: my-image-name:my-tag
restart: unless-stopped
volumes:
*default-volumes
networks:
my-network:
services:
service1:
<<: *default-service
image: service1-image:tag
service2:
<<: *default-service
image: service2-image:tag
volumes:
*default-volumes
- service2:/path/on/container
networks:
my-network:
volumes:
service2: {}
Does anyone have an idea how to achieve this goal? Thanks in advance.
Edit 1:
As David Maze pointed out: There is no valid yaml solution to this problem. He also found a similar question (Is there a way to alias/anchor an array in YAML?) in which some kind of reuse is described.
I ended up using the following result:
version: '2.4'
x-volumes:
- &volume-localtime
/etc/localtime:/etc/localtime:ro
x-default-service: &default-service
image: my-image-name:my-tag
restart: unless-stopped
volumes:
- *volume-localtime
networks:
my-network:
services:
service1:
<<: *default-service
image: service1-image:tag
service2:
<<: *default-service
image: service2-image:tag
volumes:
- *volume-localtime
- service2:/path/on/container
networks:
my-network:
volumes:
service2: {}