在具有桥接网络的Docker容器中映射主机的/etc/hosts

4
我有一台主机,其中在其/etc/hosts文件中定义了一些主机解析。
在这台机器上,我运行了配置有桥接网络的Docker容器。
由于我不在主机网络上,因此我的Docker容器无法访问主机/etc/hosts文件的主机定义。
不幸的是,目前不能使用DNS。
我的问题是如何在使用桥接网络的情况下利用这些定义在我的容器中?我阅读到将主机的/etc/hosts文件挂载到容器中不是一个好的选择,因为那是由docker守护程序在内部处理的。
您知道还有什么其他方法可以实现这个功能吗?

这个可能吗?将您的主机/etc/hosts复制到容器/tmp/foo,然后将/tmp/foo附加到容器的/etc/hosts。 - dormi330
2个回答

4
我认为最好使用--add-host的命令行选项将条目添加到容器的/etc/hosts中。以下是来自官方Docker参考文档的摘录。

Managing /etc/hosts

Your container will have lines in /etc/hosts which define the hostname of the container itself as well as localhost and a few other common things. The --add-host flag can be used to add additional lines to /etc/hosts.

$ docker run -it --add-host db-static:86.75.30.9 ubuntu cat /etc/hosts
172.17.0.22     09d03f76bf2c
fe00::0         ip6-localnet
ff00::0         ip6-mcastprefix
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters
127.0.0.1       localhost
::1               localhost ip6-localhost ip6-loopback
86.75.30.9      db-static

3
你有两个选项:
docker run -v /etc/hosts:/etc/hosts 这个选项的问题是,你的容器 hosts 文件会被覆盖,如果你想在那个 Docker 网络中联系任何其他服务,这会产生反作用。
因此,我会这样做:
docker run -v /etc/hosts:/tmp/hosts 并在你的镜像中使用一个 entrypoint,它执行以下操作之一
cat /tmp/hosts >> /etc/hosts
a) 你想过滤掉一些行,比如 localhost,或者使用 grep 选择特定的行 b) 你想确保不会在每个容器启动时重复这个步骤,所以写一个信号量或类似的东西(一个文件,检查文件等)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接