To connect to your host machine’s localhost (or services running on it) from inside a Docker container, use one of the following methods:
1. Use host.docker.internal
(Recommended for macOS/Windows)
This DNS name automatically resolves to your host machine’s IP address.
Example:
curl http://host.docker.internal:3000 # Replace 3000 with your host service's port
Note:
- Works out-of-the-box on Docker Desktop for macOS/Windows.
- For Linux, add
--add-host=host.docker.internal:host-gateway
when starting the container:
docker run --add-host=host.docker.internal:host-gateway my-image
2. Use the Host’s Gateway IP (Linux Default Bridge Network)
The host’s IP is typically the Docker network gateway (e.g., 172.17.0.1
).
Steps:
- Find the gateway IP inside the container:
ip route show default | awk '/default/ {print $3}'
- Use this IP to connect:
curl http://172.17.0.1:3000
3. Use --network="host
(Share Host Network)
Run the container with the host’s network stack.
docker run --network="host" my-image
Now localhost
inside the container refers to the host’s localhost:
curl http://localhost:3000
Warning: This removes network isolation between the container and host (security risk).
4. Use the Host’s Public IP
If the host service is bound to 0.0.0.0
(not just 127.0.0.1
), use the host’s public IP:
curl http://<host-machine-ip>:3000
Find the host’s IP with:
# On the host machine:
hostname -I | awk '{print $1}'
Summary Table
Method | Platform | Command/Address | Notes |
---|---|---|---|
host.docker.internal | macOS/Windows | http://host.docker.internal:PORT | Automatic resolution |
--add-host (Linux) | Linux | host.docker.internal:host-gateway | Requires docker run --add-host |
Host Gateway IP (e.g., 172.17.0.1 ) | Linux | Use ip route to find IP | Manual setup, varies by network |
--network="host" | All | http://localhost:PORT | Shares host network (no isolation) |
Host Public IP | All | <host-ip>:PORT | Host service must bind to 0.0.0.0 |
Common Fixes
- Host service not reachable? Ensure it’s bound to
0.0.0.0
, not127.0.0.1
. - Connection refused? Check firewall rules or host service availability.
host.docker.internal
not working on Linux? Use the--add-host
flag as shown above.
By choosing the right method for your environment, you can seamlessly connect your Docker container to services running on the host machine.