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
.
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/
Add standard host file -
docker run -it ubuntu cat /etc/hosts
Add a mapping for server 'foo' -
docker run -it --add-host foo:10.0.0.3 ubuntu cat /etc/hosts
Add mappings for multiple servers
docker run -it --add-host foo:10.0.0.3 --add-host bar:10.7.3.21 ubuntu cat /etc/hosts
Reference -
http://jasani.org/2014/11/19/docker-now-supports-adding-host-mappings/
Add to your run command -v /etc/hosts:/etc/hosts
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.
If you are using docker-compose.yml
, the corresponding property is:
services:
xxx:
network_mode: "host"
Source
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
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 :
- 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.
- 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.