Docker Compose 为 YAML 别名和锚点合并数组

And*_*ara 3 yaml docker

我有以下损坏的 docker-compose 文件

version: '3.4'

x-vols1: &vols-1
    - /home/:/home/

x-vols2: &vols-2
    - /tmp/:/tmp/

services:
    app1:
        container_name: app1
        image: app1
        volumes:
            <<: *vols-1
    app2:
        container_name: app2
        image: app2
        volumes:
            <<: *vols-1
            <<: *vols-2
Run Code Online (Sandbox Code Playgroud)

这失败并出现以下错误

$ docker-compose -f test.yaml config
ERROR: yaml.constructor.ConstructorError: while constructing a mapping
  in "./test.yaml", line 14, column 13
expected a mapping for merging, but found scalar
  in "./test.yaml", line 4, column 7
Run Code Online (Sandbox Code Playgroud)

问题 1:如何合并数组docker-compose?我尝试使用的语法是用于合并字典的语法

问题2:如果没有办法合并数组,是否有解决方法?

用例:我有多个服务,其中一些映射一些卷,其他映射其他卷,其他映射所有卷。我不想重复自己。

谢谢!

BMi*_*tch 5

Yaml 合并语法用于合并映射,而不是用于数组。有关更多信息,请参阅此问题。但是,如果您只是添加单个卷,则不需要合并任何内容。只需将别名作为数组条目插入:

version: '3.4'

x-vols1: &vols-1
    "/home/:/home/"

x-vols2: &vols-2
    "/tmp/:/tmp/"

services:
    app1:
        container_name: app1
        image: app1
        volumes:
            - *vols-1
    app2:
        container_name: app2
        image: app2
        volumes:
            - *vols-1
            - *vols-2
Run Code Online (Sandbox Code Playgroud)


And*_*ara 3

docker-compose可以通过使用多个文件(每个卷一个)来实现所需的行为。请注意,锚点和别名不是必需的,但请保留它们以与问题保持一致。

base.yaml

version: '3.4'

services:
    app1:
        container_name: app1
        image: app1
    app2:
        container_name: app2
        image: app2
Run Code Online (Sandbox Code Playgroud)

vol1.yaml

version: '3.4'

x-vols1: &vols-1
    volumes:
        - /home/:/home/

services:
    app1:
        container_name: app1
        image: app1
        <<: *vols-1
    app2:
        container_name: app2
        image: app2
        <<: *vols-1
Run Code Online (Sandbox Code Playgroud)

vol2.yaml

version: '3.4'

x-vols2: &vols-2
    volumes:
        - /tmp/:/tmp/

services:
    app2:
        container_name: app2
        image: app2
        <<: *vols-2
Run Code Online (Sandbox Code Playgroud)

验证为

$ docker-compose -f base.yaml -f vol1.yaml -f vol2.yaml config
Run Code Online (Sandbox Code Playgroud)

结果

services:
  app1:
    container_name: app1
    image: app1
    volumes:
    - /home:/home:rw
  app2:
    container_name: app2
    image: app2
    volumes:
    - /home:/home:rw
    - /tmp:/tmp:rw
version: '3.4'
Run Code Online (Sandbox Code Playgroud)

附加文档https://docs.docker.com/compose/extends/

  • 在本例中,您已从合并数组更改为合并映射。为此不需要多个撰写文件。 (2认同)
  • 的确。看起来 compose 在合并方面比 yaml 做得更好。如果您开始变得太复杂,那么可能值得考虑一些模板工具,例如 gomplate 和 jsonnet。 (2认同)