From inside of a Docker container, how do I connect to the localhost of the machine?

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:

  1. Find the gateway IP inside the container:
   ip route show default | awk '/default/ {print $3}'
  1. 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

MethodPlatformCommand/AddressNotes
host.docker.internalmacOS/Windowshttp://host.docker.internal:PORTAutomatic resolution
--add-host (Linux)Linuxhost.docker.internal:host-gatewayRequires docker run --add-host
Host Gateway IP (e.g., 172.17.0.1)LinuxUse ip route to find IPManual setup, varies by network
--network="host"Allhttp://localhost:PORTShares host network (no isolation)
Host Public IPAll<host-ip>:PORTHost service must bind to 0.0.0.0

Common Fixes

  • Host service not reachable? Ensure it’s bound to 0.0.0.0, not 127.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.

Leave a Reply

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