'In docker-compose, is it possible to reuse volume configuration between services?
I'm trying using a setup similar to the following:
version: '3.4'
x-my-volumes: &volumes
- '../src:/var/www/src/:cached'
- '../static:/var/www/static/:cached'
services:
webserver:
build: ./.docker/webserver
volumes:
- *volumes
- './serverlogs/:/var/www/serverlogs/:delegated'
node:
build: ./.docker/node
volumes:
- *volumes
I set up the "shared" volumes in the x-my-volumes
section and give it an anchor of "volumes", which I try to utilise in my services. The main thing, though, is that the services have other volume mounts aside from the shared one. This doesn't work, with errors such as "contains an invalid type, it should be an array
" when doing a docker-compose up
.
Is this possible for docker-compose? I realise I can just copy and paste the volume mounts for each service in my real world scenario its 10+ services and 10+ volumes, so it's a lot of ugly duplication.
Solution 1:[1]
If the volume array is exactly the same between services, you can do this:
services:
webserver:
volumes: &volumes
- one:one
- two:two
node:
volumes: *volumes
If you wish to extend the array and add elements to it in some services, this does not seem to be supported in YAML as indicated by this GitHub issue and this StackOverflow question.
Perhaps to give you another approach to consider (although I am not sure it will be helpful for your use case):
In many of my docker compose, I define a "base" service, and then I can inherit some attributes of this service by other services, by using YAML merge. Consider this example:
services:
bash:
build: .
entrypoint: /bin/bash
<<: &default
image: dannyben/borg-client
volumes:
- one:one
- two:two
init:
<<: *default
command: init -e repokey-blake2
backup:
<<: *default
command: create --stats --progress ::initial-backup /borg/source
Using this approach I can have complex docker-compose files expressed in a very readable manner.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |