我正在尝试使用bash将docker-compose.yml文件与docker-compose2.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获得此输出?
我认为您无需编写脚本就可以在本机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: {}
可能有一种本机方式,但我只是将标准输出重定向到文件:
$ 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/。
Docker Compose config command完全满足您的需求,它需要多个撰写文件并将其合并。
只需使用多个-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
查看文档以获取有关how to specify multiple compose files的更多详细信息。