如何将主机名添加到同一个dockernetworking上的容器?

假设我有一个有两个容器的docker撰写文件。 两者在他们的/ etc / hosts文件中相互引用。 容器A有容器B的参考,反之亦然。 而这一切都是自动发生的。 现在我想在A的主机文件中添加一个或多个主机名到B. 我怎么能这样做? 有没有一种特殊的方式可以在Docker Compose中实现?

例:

service-b my-custom-hostname

是。 在你的撰写文件中,你可以指定networking别名 。

services: db: networks: default: aliases: - database - postgres 

在这个例子中, db服务可以通过使用dbdatabasepostgres的默认networking上的其他容器来访问。

您也可以使用--alias= docker network connect命令和--alias=选项将别名添加到正在运行的容器中 。

Docker compose具有extra_hostsfunction,允许将其他条目添加到容器的主机文件中。

泊坞窗,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组成与新的docker1.9networkingfunction :

 $ docker-compose --x-networking up -d Starting tmp_web1_1 Starting tmp_web2_1 Starting tmp_web3_1 

并查看第一个容器中的hosts文件。 显示其他容器,以及其他自定义条目:

 $ 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 

如果我正确理解你的问题,你可以通过–add-host标志传递你的主机的/ etc / hosts文件中引用的主机名:

 $ docker run ... --add-host="droid" 

您的主机的/ etc / hosts需要以下条目:xx.xx.xx.xx droid

当然,xx.xx.xx.xx将需要从刚刚使用“docker run”命令启动的容器中进行访问。 你可以有一个或多个–add-host =“xyz”。

关于–add-host的更多细节在这里:

http://docs.docker.com/v1.8/reference/commandline/run/