DEV3 Technologies home

DEV3 Developer Forum

Why can't my Docker container connect to localhost or the database on my host machine?

DevOps helpSolved0 views
dev3 ·

Inside my container, connecting to localhost:5432 fails with "connection refused", though the database works fine from my laptop terminal. How do I reach a service running on the host or in another container?

#docker#networking#troubleshooting

0

1 reply

dev3 · Accepted answer

Inside a container, localhost means the container itself. Each container has its own network namespace, so the host's services and other containers are not on it.

Another container in the same Compose project: use the service name.

services:
  app:
    environment:
      DATABASE_URL: postgres://user:pass@db:5432/app
  db:
    image: postgres:17

Compose creates a default network where service names resolve through DNS. Use the container port (5432), not a published host port. Services started with plain docker run need a user-defined network (docker network create appnet, then --network appnet) for name resolution.

A service on the host machine

  • Docker Desktop (macOS, Windows): use host.docker.internal.
  • Linux: add a mapping in Compose and use the same name:
services:
  app:
    extra_hosts:
      - "host.docker.internal:host-gateway"

Then connect to host.docker.internal:5432. (The older route is the bridge gateway IP, commonly 172.17.0.1.)

  • The host service must listen on an address reachable from the bridge network. If PostgreSQL or MySQL listens only on 127.0.0.1, set listen_addresses / bind-address to include the Docker bridge interface, and allow it in pg_hba.conf and the firewall. This exposes the service to more interfaces, so restrict by firewall.
  • network_mode: host (works natively on Linux) shares the host network, so localhost works, but it disables port isolation and port mappings.

From the host to a container: publish a port (ports: ["5432:5432"]) and connect to localhost:5432. Bind to 127.0.0.1:5432:5432 to keep it private.

Debug steps

docker compose exec app sh
getent hosts db            # does the name resolve?
nc -zv db 5432             # is the port open?
docker network inspect <project>_default

Also check that the database has finished starting (healthchecks, see the Compose topic) and that credentials and database names match.

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.