Docker Compose Extra Hosts
Sometimes you need your container to resolve a specific hostname to a specific IP address, overriding standard DNS. In Docker Compose, the extra_hosts configuration allows you to modify the container's /etc/hosts file.
Syntax
extra_hosts is defined as a list of hostname:IP mappings.
services:
app:
image: my-app
extra_hosts:
- "somehost:162.242.195.82"
- "otherhost:50.31.209.229"
Inside the container, /etc/hosts will include:
162.242.195.82 somehost
50.31.209.229 otherhost
Common Use Cases
1. Accessing the Host Machine (Linux)
As discussed in our Host Networking guide, Linux containers don't support host.docker.internal by default. You can enable it using the special host-gateway value.
services:
web:
image: nginx
extra_hosts:
- "host.docker.internal:host-gateway"
This maps host.docker.internal to the IP address of the host gateway, allowing your container to talk to services running on your local machine (e.g., a local Postgres database not in Docker).
2. Mocking DNS for Development
If your application connects to a production domain (e.g., api.example.com), but you want to redirect that traffic to a local test server or another container during development, you can use extra_hosts.
services:
backend:
image: my-backend
# ...
frontend:
image: my-frontend
extra_hosts:
- "api.example.com:172.17.0.1" # Redirect to local IP
3. Communicating Between Containers (Legacy)
While modern Docker Compose setups should use Docker Networks and service names for discovery (e.g., connecting to http://db instead of an IP), extra_hosts can be useful for legacy applications that require specific hardcoded hostnames.
IPv6 Support
You can also map IPv6 addresses if your Docker daemon is configured for it.
extra_hosts:
- "somehost:2001:db8::10"
Simplify Your Networking
Managing DNS records and host files manually can be error-prone.
Hostim.dev provides a platform where service discovery just works. Deploy your stack and let us handle the networking complexity.