shell 如何将Docker Compose文件与Bash合并

eh57zj3b  于 7个月前  发布在  Shell
关注(0)|答案(3)|浏览(59)

我正在尝试使用bash将docker-compose.yml文件与docker-compose 2.yml文件合并。

docker-compose.yml:

version: "3"

services:
  nexus:
    image: sonatype/nexus3
    volumes:
      - "/opt/nexus3/nexus-data:/nexus-data"
    ports:
      - "8081:8081"

volumes:
  nexus-data: {}

docker-compose2.yml:

version: "3"

services:
  nexus2:
    image: sonatype/nexus3
    volumes:
      - "/opt/nexus3/nexus-data:/nexus-data"
    ports:
      - "8082:8082"

volumes:
  nexus-data: {}

我要输出:

version: "3"

services:
  nexus:
    image: sonatype/nexus3
    volumes:
      - "/opt/nexus3/nexus-data:/nexus-data"
    ports:
      - "8081:8081"

  nexus2:
    image: sonatype/nexus3
    volumes:
      - "/opt/nexus3/nexus-data:/nexus-data"
    ports:
      - "8082:8082"
volumes:
  nexus-data: {}

如何使用bash获得此输出?

tct7dpnv

tct7dpnv1#

Docker Compose config command正是你需要的,它需要多个compose文件并合并它们。
只需使用多个-f标志传递它们:

docker-compose -f docker-compose.yml -f docker-compose2.yml config

或者使用一个环境变量:

COMPOSE_FILE=docker-compose.yml:docker-compose2.yml docker-compose config

同样的方法对每个Docker Compose命令都有效,所以如果你的最终目标是,例如,设置你的项目,你可以直接运行:

docker-compose -f docker-compose.yml -f docker-compose2.yml up

有关如何指定多个合成文件的详细信息,请参阅文档。

s8vozzvw

s8vozzvw2#

我不认为你可以在native bash中不写脚本就做到这一点(简单地作为一行程序)。我很好奇,所以我做了一个快速搜索,发现了一个yaml操作工具,它支持合并yaml(docker-compose)文件,看起来适合你的用例。
我使用brew安装在macOS上,但也有Linux的说明-https://mikefarah.github.io/yq/

brew install yq

显示现有文件:

$ cat file1.yaml
version: "3"

services:
  nexus:
    image: sonatype/nexus3
    volumes:
      - "/opt/nexus3/nexus-data:/nexus-data"
    ports:
      - "8081:8081"

volumes:
  nexus-data: {}

$ cat file2.yaml
version: "3"

services:
  nexus2:
    image: sonatype/nexus3
    volumes:
      - "/opt/nexus3/nexus-data:/nexus-data"
    ports:
      - "8082:8082"

volumes:
  nexus-data: {}

合并两个文件输出到标准输出:

$ yq m file1.yaml file2.yaml
services:
  nexus:
    image: sonatype/nexus3
    ports:
    - 8081:8081
    volumes:
    - /opt/nexus3/nexus-data:/nexus-data
  nexus2:
    image: sonatype/nexus3
    ports:
    - 8082:8082
    volumes:
    - /opt/nexus3/nexus-data:/nexus-data
version: "3"
volumes:
  nexus-data: {}

可能有一种原生方式,但我只是将stdout重定向到一个文件:

$ yq m file1.yaml file2.yaml > file3.yaml
$ cat file3.yaml
services:
  nexus:
    image: sonatype/nexus3
    ports:
    - 8081:8081
    volumes:
    - /opt/nexus3/nexus-data:/nexus-data
  nexus2:
    image: sonatype/nexus3
    ports:
    - 8082:8082
    volumes:
    - /opt/nexus3/nexus-data:/nexus-data
version: "3"
volumes:
  nexus-data: {}

在他们的文档中有很多示例供您探索-https://mikefarah.github.io/yq/merge/

sqserrrh

sqserrrh3#

有一种新的方法可以做到这一点,你可以使用docker compose convert这里是适合你正在尝试做的事情的例子:

docker compose -f docker-compose.yml -f docker-compose2.yml convert > output.yml

Official documentation

相关问题