How can you make the docker container use the host

2019-01-31 11:49发布

I want to make it so that the docker container I spin up use the same /etc/hosts settings as on the host machine I run from. Is there a way to do this?

I know there is an --add-host option with docker run but that's not exactly what I want because the host machine's /etc/hosts file may be different on different machines so it's not great for me to hardcode exact IP/hosts with --add-host.

标签: docker
7条回答
Bombasti
2楼-- · 2019-01-31 12:28

If trusted users start your containers, you could use a shell function to easily "copy" the /etc/hosts entries that you need:

add_host_opt() { awk "/\\<${1}\\>/ {print \"--add-host $1:\" \$1}" /etc/hosts; }

You can then do:

docker run $(add_host_opt host.name) ubuntu cat /etc/hosts

That way you do not have to hard-code the IP addresses.

查看更多
Viruses.
3楼-- · 2019-01-31 12:31

Use --network=host in the docker run command. This tells Docker to make the container use the host's network stack. You can learn more here: https://docs.docker.com/engine/userguide/networking/

查看更多
萌系小妹纸
4楼-- · 2019-01-31 12:38

Add to your run command -v /etc/hosts:/etc/hosts

查看更多
地球回转人心会变
5楼-- · 2019-01-31 12:46

If you are running a virtual machine for running docker containers, if there are hosts (VMs, etc) you want your containers to be aware of, depending on what VM software you are using, you will have to ensure that there are entries on the host machine (hosting the VM) for whatever machines you want the containers to be able to resolve. This is because the VM and it's containers will have the IP of the host machine (of the VMs) in their resolv.conf

查看更多
在下西门庆
6楼-- · 2019-01-31 12:49

If you are using docker-compose.yml, the corresponding property is:

services:
  xxx:
    network_mode: "host"

Source

查看更多
乱世女痞
7楼-- · 2019-01-31 12:50

IMO, passing --network=host option while running the docker is a better option as suggested by d3ming over other options as suggested by other answers :

  1. Any change in host's /etc/hosts is immediately available to container, which is what probably you want if you have such requirement at the first place.
  2. Its probably not a good idea to use -v option to mount host's /etc/hosts as any unintended change by container will spoil the hosts config.
查看更多
登录 后发表回答