An API container must reach its database container, and localhost inside a container points only to that container itself. A user-defined Docker network lets containers find each other by name, like db:5432. Use it whenever two or more containers talk to each other. Publishing ports with -p is for reaching a container from the host, not for container to container traffic, and that mix-up causes many "connection refused" errors.