How can you make the Docker container use the host machine's '/etc/hosts' file?
Solution 1:
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.
Solution 2:
Add a standard hosts 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 - Docker Now Supports Adding Host Mappings
Solution 3:
extra_hosts (in docker-compose.yml)
https://docs.docker.com/compose/compose-file/
Add hostname mappings. Use the same values as the docker client --add-host parameter.
extra_hosts:
- "somehost:162.242.195.82"
- "otherhost:50.31.209.229"
Solution 4:
If you are using docker-compose.yml
, the corresponding property is:
services:
xxx:
network_mode: "host"
Source
Solution 5:
Also you can install dnsmasq to the host machine, by the command:
sudo apt-get install dnsmasq
And then you need to add the file /etc/docker/daemon.json with content:
{
"dns": ["host_ip_address", "8.8.8.8"],
}
After that, you need to restart the Docker service by command sudo service docker restart
This option forces to use the host DNS options for every Docker container. Or you can use it for a single container, and the command-line options are explained by this link. Also docker-compose options are supported (you can read about it by this link).