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

谁说胖子不能爱 提交于 2019-12-06 10:46:47

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

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 )

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