如何将主机名添加到同一 docker 网络上的容器?
How can I add hostnames to a container on the same docker network?
假设我有一个 docker 包含两个容器的组合文件。两者在 /etc/hosts 文件中相互引用。容器 A 有容器 B 的引用,反之亦然。而这一切都是自动发生的。现在我想在 A 的主机文件中为 B 添加一个或多个主机名。我该怎么做呢?在 Docker Compose 中有什么特殊的方法可以做到这一点?
示例:
172.0.10.166 服务-b 我的自定义主机名
如果我对你的问题的理解正确,你可以通过 --add-host 标志传递主机的 /etc/hosts 文件中引用的主机名:
$ docker run ... --add-host="droid"
您的主机 /etc/hosts 需要以下条目:
xx.xx.xx.xx 机器人
当然,xx.xx.xx.xx 需要从您刚开始使用 'docker run' 命令的容器内部访问。您可以有一个或多个 --add-host="xyz".
有关 --add-host 的更多详细信息:
Docker compose 具有 extra_hosts 功能,允许将其他条目添加到容器的主机文件中。
示例
docker-compose.yml
web1:
image: tomcat:8.0
ports:
- 8081:8080
extra_hosts:
- "somehost:162.242.195.82"
- "otherhost:50.31.209.229"
web2:
image: tomcat:8.0
ports:
- 8082:8080
web3:
image: tomcat:8.0
ports:
- 8083:8080
演示主机文件条目
运行 docker 与新 docker 1.9 networking feature:
$ docker-compose --x-networking up -d
Starting tmp_web1_1
Starting tmp_web2_1
Starting tmp_web3_1
并查看第一个容器中的主机文件。显示其他容器,以及额外的自定义条目:
$ docker exec tmp_web1_1 cat /etc/hosts
..
172.18.0.4 web1
172.18.0.2 tmp_web2_1
172.18.0.3 tmp_web3_1
50.31.209.229 otherhost
162.242.195.82 somehost
是的。在您的撰写文件中,您可以指定 network aliases.
services:
db:
networks:
default:
aliases:
- database
- postgres
在此示例中,默认网络上的其他容器可以使用 db
、database
或 postgres
.[=19= 访问 db
服务]
您还可以 add aliases to running containers 使用带有 --alias=
选项的 docker network connect
命令。
假设我有一个 docker 包含两个容器的组合文件。两者在 /etc/hosts 文件中相互引用。容器 A 有容器 B 的引用,反之亦然。而这一切都是自动发生的。现在我想在 A 的主机文件中为 B 添加一个或多个主机名。我该怎么做呢?在 Docker Compose 中有什么特殊的方法可以做到这一点?
示例:
172.0.10.166 服务-b 我的自定义主机名
如果我对你的问题的理解正确,你可以通过 --add-host 标志传递主机的 /etc/hosts 文件中引用的主机名:
$ docker run ... --add-host="droid"
您的主机 /etc/hosts 需要以下条目: xx.xx.xx.xx 机器人
当然,xx.xx.xx.xx 需要从您刚开始使用 'docker run' 命令的容器内部访问。您可以有一个或多个 --add-host="xyz".
有关 --add-host 的更多详细信息:
Docker compose 具有 extra_hosts 功能,允许将其他条目添加到容器的主机文件中。
示例
docker-compose.yml
web1:
image: tomcat:8.0
ports:
- 8081:8080
extra_hosts:
- "somehost:162.242.195.82"
- "otherhost:50.31.209.229"
web2:
image: tomcat:8.0
ports:
- 8082:8080
web3:
image: tomcat:8.0
ports:
- 8083:8080
演示主机文件条目
运行 docker 与新 docker 1.9 networking feature:
$ docker-compose --x-networking up -d
Starting tmp_web1_1
Starting tmp_web2_1
Starting tmp_web3_1
并查看第一个容器中的主机文件。显示其他容器,以及额外的自定义条目:
$ docker exec tmp_web1_1 cat /etc/hosts
..
172.18.0.4 web1
172.18.0.2 tmp_web2_1
172.18.0.3 tmp_web3_1
50.31.209.229 otherhost
162.242.195.82 somehost
是的。在您的撰写文件中,您可以指定 network aliases.
services:
db:
networks:
default:
aliases:
- database
- postgres
在此示例中,默认网络上的其他容器可以使用 db
、database
或 postgres
.[=19= 访问 db
服务]
您还可以 add aliases to running containers 使用带有 --alias=
选项的 docker network connect
命令。