DockerCompose构建一个映像并运行多个容器

时间:2020-08-14 01:34:10

标签: docker docker-compose

我有一个docker-compose文件,可以构建4个图像并运行4个容器,这很好。但是在我用来构建4个映像的那4个Dockerfile中,唯一的区别是cmd。我只是想知道是否有更好的方法,例如只需更改cmd,即可构建一个映像并从该映像运行4个容器,

这是我的docker-compose.yml

version: '3.6'

services:
  esg_scoring.insight:
    build:
      context: .
      dockerfile: insight/Dockerfile
  esg_scoring.momentum:
    build:
      context: .
      dockerfile: momentum/Dockerfile
  esg_scoring.pulse:
    build:
      context: .
      dockerfile: pulse/Dockerfile
  esg_scoring.sasb_mapping:
    build:
      context: .
      dockerfile: sasb_mapping/Dockerfile

1 个答案:

答案 0 :(得分:1)

如果您需要多个容器运行同一映像,并且仅因启动它们的命令而有所不同,则绝对应避免使用多个docker映像,并使用同一映像。

您正在寻找docker-compose中的command指令。

此外,您可以使用YAML锚点语法重用代码块并简化代码。

这里是一个示例,该示例使用相同的映像和不同的命令来提供4个服务。您可以在default设置下放置所有共同的所有参数:

version: '3'

services:
  bash:
    build: .
    command: bash
    <<: &default
      image: me/my-image

  web:
    <<: *default
    command: bundle exec run server start

  setup:
    <<: *default
    command: bundle exec run db setup

  jobs:
    <<: *default
    command: bundle exec run job runner

此方法的优点在于,由于docker-compose build指令不在build设置之外,因此在运行default时它只会生成一次。