假设我在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"
最佳答案
是的,自从撰写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'
关于docker - 在docker-compose中创建一个全局变量od “extra_hosts”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56922773/