localhost inside a container

Why localhost in a container is not your computer.

Inside a container, localhost means the container itself. If an application in a container connects to localhost:5432, it looks for the database inside its own container, not on the host and not in the neighbouring container. This is the most frequent cause of “connection refused” for people who have just moved an application into Docker.

The right address depends on where the needed service is. A database in a neighbouring container is reachable by the container name in a shared network. A service that runs directly on the host is reachable on Docker Desktop by the name host.docker.internal. On Linux this name has to be added explicitly at start.

docker run --rm --add-host=host.docker.internal:host-gateway curlimages/curl:8.10.1 curl -s http://host.docker.internal:3000/health

The --add-host flag with the special value host-gateway adds a name to the container that points to the host. On Windows and macOS with Docker Desktop the name exists by default.

There is a flip side. A service on the host that listens only on 127.0.0.1 may not accept connections from a container, because for the host a request from a container does not come from the local interface. If reaching the host does not work, check which address the service on the host is listening on.

A common mistake is to fix the problem with the --network host flag, which turns off network isolation: the container starts using the host's network directly. On Linux this works, but the container's and host's ports get mixed up and the isolation is gone. It is better to use the right address: the container name or host.docker.internal.

Practice

  1. What localhost is

    An application in a container connects to localhost:6379. Where does it look for the service?

    • On the host
    • In a neighbouring container with that port
    • Inside the same container
    • In the Docker Hub cloud
  2. The right addresses

    Which addresses work for reaching other services from a container? Mark all correct ones.

    • The name of a neighbouring container in a shared network
    • host.docker.internal for a service on the host
    • localhost for a service on the host
    • A neighbour's IP address written into the config for good
  3. The host's name

    Which name on Docker Desktop points from a container to the host machine?