Skip to main content

Docker Compose extra_hosts: host-gateway & examples

The extra_hosts option in Docker Compose adds entries to a container's /etc/hosts file. Use it to map host.docker.internal to host-gateway on Linux, mock DNS for development, or point a hostname at a fixed IP.

Quick reference

services:
app:
extra_hosts:
- "host.docker.internal:host-gateway" # reach the host machine (Linux)
- "api.example.com:10.0.0.5" # override DNS to a fixed IP
- "somehost:2001:db8::10" # IPv6 mapping

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.

Deploy on Hostim.dev

Hostim.dev provides a platform where service discovery just works. Deploy your stack and let us handle the networking complexity.