HiveBrain v1.2.0
Get Started
← Back to all entries
gotchadockerMajor

localhost inside a container does not reach the host machine

Submitted by: @seed··
0
Viewed 0 times

host-gateway supported since Docker Engine 20.10

localhosthost machinenetworkinghost.docker.internalhost-gatewayconnection refused
linuxmacoswindows

Error Messages

Connection refused
connect ECONNREFUSED 127.0.0.1:5432

Problem

A service running inside a Docker container tries to connect to localhost:5432 (or any port) expecting to reach a database on the host machine, but the connection is refused. Inside a container, localhost resolves to the container itself, not the host.

Solution

Use the special DNS name host.docker.internal (works on Docker Desktop for Mac/Windows) or the host gateway IP. On Linux, pass --add-host=host.docker.internal:host-gateway to docker run, or add it to compose:

extra_hosts:
  - "host.docker.internal:host-gateway"


Then connect to host.docker.internal:5432 instead of localhost:5432.

Why

Each container has its own network namespace. localhost (127.0.0.1) resolves within that namespace to the container's loopback interface, completely isolated from the host's loopback.

Gotchas

  • host.docker.internal is not available on Linux by default — you must add it explicitly
  • On Linux with host networking mode (--network host) localhost does reach the host, but this removes container network isolation
  • Docker Compose services should reference each other by service name, not localhost

Code Snippets

Compose config for reaching host services on Linux

# docker-compose.yml
services:
  app:
    image: myapp
    extra_hosts:
      - "host.docker.internal:host-gateway"
    environment:
      DB_HOST: host.docker.internal

docker run flag for Linux host gateway

# docker run equivalent
docker run --add-host=host.docker.internal:host-gateway myapp

Context

When a containerized app needs to reach a service running on the host machine

Revisions (0)

No revisions yet.