Map host's /etc/hosts in a Docker container having bridge networking

扶醉桌前 提交于 2019-12-10 10:56:17

问题


I have a host machine with some hosts resolution defined in its /etc/hosts file.

On this machine I'm running my Docker containers configured with a Bridge network.
Since I'm not on the host network my Docker containers have no access of the hosts definitions of my machine /etc/hosts file.

Unfortunately having a DNS it is not an option at the moment.

My question is how can I make use of those definitions in my containers using bridge networking? I read mounting the hosts /etc/hosts file in the container is not a good choice since that's handled internally by the docker deamon.
Do you know how else I can achieve this?


回答1:


I think it may be better to use the command-line option of --add-host to add entries into the /etc/hosts of the container.

Here is an excerpt from the official Docker Reference

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



回答2:


You have 2 options

docker run -v /etc/hosts:/etc/hosts <yourimage>

the problem with the option is, that your container hosts file is overwritten, which will backfire if you want to contact any other service in that docker-network.

Thus i would do

docker run -v /etc/hosts:/tmp/hosts <yourimage>

And use a entrypoint in your image, which does something among this lines

cat /tmp/hosts >> /etc/hosts

a) You want to filter out some lines like localhost, or select specific lines using grep b) You want to ensure you do not repeat this on every container bootstrap, so write a semaphore or similar ( a file, check the file whatever )



来源:https://stackoverflow.com/questions/41440650/map-hosts-etc-hosts-in-a-docker-container-having-bridge-networking

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!