Docker /etc/hosts Only Accepts IPs, Not Hostnames

📖 1 minute read

TIL you can’t do this in a Docker container:

echo "proxy.example.com www.api.com" >> /etc/hosts

I wanted to redirect www.api.com to proxy.example.com inside a container without hardcoding the proxy’s IP address.

The problem: /etc/hosts format is strict — IP_ADDRESS hostname [hostname...]. You can’t use hostnames on the left side. Only IP addresses.

What works:

143.198.210.158 www.api.com

What doesn’t:

proxy.example.com www.api.com  # NOPE

The workaround: use Docker’s extra_hosts in docker-compose.yaml:

extra_hosts:
  - "www.api.com:143.198.210.158"

Or resolve the hostname before writing to /etc/hosts:

IP=$(getent hosts proxy.example.com | awk '{print $1}')
echo "$IP www.api.com" >> /etc/hosts

/etc/hosts is old-school. It predates DNS. It doesn’t do hostname resolution — it IS the resolution.

Daryle De Silva

VP of Technology

11+ years building and scaling web applications. Writing about what I learn in the trenches.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *