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


When you're inside a Docker container, you cannot directly access the localhost of your host machine. By default, localhost refers to the container itself, not the host machine. However, there are several ways to connect to the host machine's localhost from inside a Docker container.


Use host.docker.internal (Windows and macOS)

Docker provides a special hostname, host.docker.internal, that resolves to the IP address of the host machine. This is the simplest way to access the host machine from within a container.

Example:

From inside the container, you can run something like

http://host.docker.internal:8080
  • This command connects to the service running on localhost:8080 on your host machine.

2. Use Docker Host Networking (Linux Only)

If you're running Docker on a Linux machine, you can use Docker’s --network host option, which allows containers to share the host's network stack.

Example:

When you run your container

docker run --rm --network host <image-name>

In this case, localhost inside the container will refer to the host machine's network, and you can connect to services running on the host machine without any special configuration.


Find and Use the Host’s IP Address (Cross-platform)

Another way to connect to the host machine from inside a container is to use the host’s actual IP address. Here's how you can do this:

  1. Find Your Host IP Address:

    • On Linux/macOS, you can find it using: 
      ip addr show docker0
      

    • On Windows, use: 
      ipconfig
      

      Look for the IP of your network interface or docker0 bridge.

  2. Use the Host IP Address: From inside the container, you can now connect to this IP address, just like you would with any remote server.
    http://<host-ip>:8080
    

Expose Ports on the Host Machine

If you want to expose a port on the host machine to make it accessible to containers:

When you run your container, expose the necessary port using the -p option:

docker run -p 8080:8080 <image-name>

This will map port 8080 in the container to port 8080 on the host machine, allowing you to access it from within the container using the host.docker.internal or the host's IP address.


In Summery

host.docker.internal – Use this for Windows/macOS to access the host machine.

Host networking (--network host) – Use on Linux to share the network stack between host and container.