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-gatewayto get the same name. In Compose, useextra_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 makeslocalhostmean 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.
Read more