CodePark/ questions / Networking & ports
START PRACTICINGPRACTICE
Backend question · Docker › Networking & ports

Your containerised API is configured with DATABASE_URL=postgres://localhost:5432/app, and Postgres runs directly on your laptop (not in Docker). The connection is refused. Why, and what are the options?

Inside a container, localhost means the container itself, not your laptop (the host). Nothing listens on port 5432 inside the API container, so the connection is refused.

Your options:

  • Docker Desktop: use the special name host.docker.internal. It points to the host.
  • Linux with Docker Engine: add --add-host=host.docker.internal:host-gateway to get the same name. In Compose, use extra_hosts.
  • Run Postgres in a container on the same network and connect by its name. This is often the cleaner option.
  • Host networking (--network host) also makes localhost mean the host. But it removes network isolation between the container and the host.

When you use host.docker.internal, Postgres on the host must also listen on an address the container can reach. Its config must also allow the connection.

  • Inside a container, localhost means the container itself.
  • On Docker Desktop, use host.docker.internal to reach the host.
  • On Linux, map host.docker.internal with host-gateway.
  • Or run the database as a container on the same network.