在docker-compose中创建一个全局变量od“ extra_hosts”

时间:2019-07-07 13:53:39

标签: docker docker-compose

让我们假设我在docker-compose中有十个服务,每个此服务都需要具有四个记录的相同extra_hosts。 我想只定义一次extra_hosts,仅将其包括在每个服务中。

有可能吗?

version: '3.7'
services:

  web:
    build:
      context: ./apache
      dockerfile: dockerfile_apache2
    image: debian:latest
    container_name: hsthttp1
    extra_hosts:
     - "somehost1:162.242.195.82"
     - "somehost2:162.242.195.83"
     - "somehost3:162.242.195.84"
     - "somehost4:162.242.195.85"
  web2:
    build:
      context: ./apache
      dockerfile: dockerfile_apache2
    image: debian:latest
    container_name: hsthttp2
    extra_hosts:
     - "somehost1:162.242.195.82"
     - "somehost2:162.242.195.83"
     - "somehost3:162.242.195.84"
     - "somehost4:162.242.195.85"
  web3:
    build:
      context: ./apache
      dockerfile: dockerfile_apache2
    image: debian:latest
    container_name: hsthttp3
    extra_hosts:
     - "somehost1:162.242.195.82"
     - "somehost2:162.242.195.83"
     - "somehost3:162.242.195.84"
     - "somehost4:162.242.195.85"

1 个答案:

答案 0 :(得分:0)

是的,自撰写3.4版本以来,可以使用Extension fields定义可重用的片段:

根据您的情况,可以使用next:

docker-compose.yaml:

version: '3.7'

x-extra_hosts:
  &default-extra_hosts
  - "somehost1:162.242.195.82"
  - "somehost2:162.242.195.83"
  - "somehost3:162.242.195.84"
  - "somehost4:162.242.195.85"

services:
  web:
    image: debian:latest
    container_name: hsthttp1
    extra_hosts: *default-extra_hosts
  web2:
    image: debian:latest
    container_name: hsthttp2
    extra_hosts: *default-extra_hosts
  web3:
    image: debian:latest
    container_name: hsthttp3
    extra_hosts: *default-extra_hosts

上面,我们定义了一个全局&default-extra_hosts,稍后在每个服务中,我们都可以使用*default-extra_hosts来引用它。

您可以使用docker-compose config快速检查效果,如下所示:

shubuntu1@shubuntu1:~/try$ docker-compose config
services:
  web:
    container_name: hsthttp1
    extra_hosts:
    - somehost1:162.242.195.82
    - somehost2:162.242.195.83
    - somehost3:162.242.195.84
    - somehost4:162.242.195.85
    image: debian:latest
  web2:
    container_name: hsthttp2
    extra_hosts:
    - somehost1:162.242.195.82
    - somehost2:162.242.195.83
    - somehost3:162.242.195.84
    - somehost4:162.242.195.85
    image: debian:latest
  web3:
    container_name: hsthttp3
    extra_hosts:
    - somehost1:162.242.195.82
    - somehost2:162.242.195.83
    - somehost3:162.242.195.84
    - somehost4:162.242.195.85
    image: debian:latest
version: '3.7'