Docker Compose "connection refused" between containers: DNS resolves, the port is not listening yet
verbatim errorError: connect ECONNREFUSED 172.18.0.3:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1607:16)
Problem
Two services in Compose, app and db. On cold start:
Error: connect ECONNREFUSED 172.18.0.3:5432
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1607:16)The service name db resolves fine — the error shows the resolved IP. Restarting the app container manually usually works. Everyone blamed Docker networking; the network was never the problem.
Root cause
ECONNREFUSED with a resolved address means the TCP connection reached the container and nothing was listening yet. Postgres takes seconds to initialize on first boot (initdb, WAL setup), and depends_on without a health check only orders start, not readiness. Your app starts, connects once, fails, and (depending on your app) dies or gives up permanently.
fix preview — first 3 of 16 lines (yaml), truncated:
services:
db:
image: postgres:16
… 13 more lines in the fix🔒 the fix — including 2 code blocks — is members-only. $1/mo unlocks everything.