debugMajor
Docker container cannot connect to host localhost services
Viewed 0 times
host.docker.internalconnection refusedlocalhost dockerhost-gatewaynetwork hostcontainer networking
dockermacoslinux
Error Messages
Problem
A Docker container tries to connect to a service running on the host machine via localhost or 127.0.0.1, but the connection is refused. The service works fine from the host itself.
Solution
localhost inside a container refers to the container itself, not the host. Solutions: (1) Docker Desktop (Mac/Windows): use host.docker.internal as the hostname. (2) Linux: add --network host to docker run, or use --add-host=host.docker.internal:host-gateway (Docker 20.10+). (3) Docker Compose: add extra_hosts: ["host.docker.internal:host-gateway"]. (4) Alternative: put both services in the same Docker network and use service names. Always prefer Docker networking over host access when possible.
Why
Docker containers have their own network namespace. localhost resolves to the container loopback interface, which is isolated from the host network stack.
Revisions (0)
No revisions yet.