Docker - Append entries to the /etc/hosts file in a container using the --add-host option

by
Jeremy Canfield |
Updated: January 26 2025
| Docker articles
When creating a container using the docker run command, the --add-host command can be used to append entries to the /etc/hosts file in the container. In this example, 172.16.0.2 foo.example.com will be appended to /etc/hosts.
sudo docker run --add-host foo.example.com:172.16.0.2 --name my-container my-image:latest
Of if the container already exists the docker update command can be used.
sudo docker update --add-host foo.example.com:172.16.0.2 my-container
You can use the docker inspect command to view the JSON for the container.
~]$ sudo docker inspect my-container | jq .[].HostConfig.ExtraHosts
foo.example.com:172.16.0.2
After the container has been created and is up and running, the docker exec command can be used to examine the /etc/hosts file in the container.
~]# docker exec foo 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
172.16.0.2 foo.example.com
Did you find this article helpful?
If so, consider buying me a coffee over at