Home / Localhost / Docker container cannot reach localhost

Docker container cannot reach localhost: use host.docker.internal

Fix "connection refused" when an app in Docker calls localhost: use host.docker.internal, a Compose service name or host networking.

Inside a container, localhost means the container itself, not your computer. If your app in Docker calls localhost:3306 for a database on your computer, nothing answers. Use the right name for where the other program runs.

What to do, step by step

  1. Decide where the program you want to reach runs: on your computer, in another container, or in the same one.
  2. Another container in the same Compose file: use its service name as the host, like db, and its internal port.
  3. A program on your computer: use host.docker.internal as the host (works in Docker Desktop on Windows and macOS).
  4. On Linux, add the name yourself: --add-host=host.docker.internal:host-gateway, or the extra_hosts line in Compose below.
  5. Make sure the program on your computer listens on 0.0.0.0, not only 127.0.0.1, or the container cannot reach it.

Commands you can copy

docker run: make host.docker.internal work on Linux
docker run --add-host=host.docker.internal:host-gateway myapp
docker-compose.yml: the same, in Compose
services:
  app:
    extra_hosts:
      - "host.docker.internal:host-gateway"
Example: connect to a database on your computer
DATABASE_URL=postgres://user:pass@host.docker.internal:5432/mydb

Other causes to check

Compose: db host name not found
Both services must be in the same Compose file (or share a network). Use the service name, not container_name from another project.
Wrong port used between containers
Containers talk on the internal port (the right number in "8080:80"). The left number is only for your computer.
Database refuses the connection from the container
The database may accept only localhost logins. Allow the container network, or use a user that can connect from any host.
Linux host.docker.internal does not resolve
Add the extra_hosts line shown here. Older Docker Engine versions lack the host-gateway value.

Questions about Docker container cannot reach localhost

What does localhost mean inside a container?
The container itself. Each container has its own network space, so localhost does not reach your computer or other containers.
What is host.docker.internal?
A special name that points to your computer from inside a container. Docker Desktop provides it. On Linux you add it with host-gateway.
Can I use network_mode: host?
On Linux, yes. The container then shares your computer's network and localhost works. It does not work the same way in Docker Desktop on Windows and macOS.

Updated 2026-10-11

Config generators for this

Related pages