This post shows how to add host-entries onto /etc/hosts on docker container when it is run. For the purpose of this post, we are using CentOS/RHEL 7 host. But this should work on any Linux host capable of running latest docker versions.
Generally speaking, /etc/hosts file can not be modified before running the docker container. However, current docker has an option “–add-host” which adds host-entries onto /etc/hosts when the container is run. Below is the syntax to add host entry while creating a new docker container.
$ sudo docker run --add-host [Hostname]:[IPAddress] -ti [Source_Container_Image] /bin/bash
For example to add a new host entry (192.168.0.1 host2.test.com) use the below command:
$ sudo docker run --add-host host1.test.com:192.168.0.1 --add-host host2.test.com:192.168.0.2 -ti source_container_image /bin/bash
The example brings /etc/hosts in the new container which has host1.test.com and host2.test.com like:
[root@63933bfcd3d3 /]# cat /etc/hosts 127.0.0.1 localhost ::1 localhost ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters 192.168.0.1 host1.test.com 192.168.0.2 host2.test.com 172.17.0.4 63933bfcd3d3 [root@63933bfcd3d3 /]#