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

标签 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"

最佳答案

是的,自从撰写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/

相关文章:

mongodb - 容器启动时无法初始化MongoDB

docker - 错误包docker-ce需要container-selinux = 2.9 centos 7

javascript - Flask JavaScript文件中出现多余的字符

docker - 如何从容器使用root用户?

docker - 如何打开/运行 YML 撰写文件?

ruby-on-rails - Docker无法在Rails捆绑软件上构建安装rake

php - 使用 Laravel 在 Docker Mysql 上连接被拒绝

docker - 在Pod中获取 “ErrImageNeverPull”

带有 golang http.Get 错误 "certificate signed by unknown authority"的 Docker 容器

docker - 使用不同 docker-compose 配置构建的容器之间的可见性