#TIL : Using extra hosts to add custom ip of hostnames to Docker container

16 Mar 2022 / by KhanhIceTea

By default, all docker container using DNS server from docker host, so if you want to overwrite the specific hostnames ip address, try the flag --add-host [hostname]:[ip]

$ docker run -it --add-host db1: --add-host db2: alpine cat /etc/hosts       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters db1 db2      0bdcf2fb2216

If you use docker-compose, then add the extra-hosts param below the service you want

      - "crm.dev:host-gateway"
      - "db1:"

Bonus : host-gateway mean the ip address of the gateway of network container in, often be the docker host!

Sound good ?