Spring Boot "Connection refused" to Postgres/MySQL in CI
The JDBC driver tried to open a TCP connection and the OS refused it: nothing is listening on that host and port yet. In CI the database service is usually still starting, or the app targets the wrong hostname.
What this error means
Startup or the first repository query fails with "Connection to localhost:5432 refused" (Postgres) or "Communications link failure" (MySQL). Retried locally it works because the DB is already up.
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that
the hostname and port are correct and that the postmaster is accepting TCP/IP connections.Common causes
The app starts before the DB service is ready
A GitHub Actions service container is booting; the app connects during the window before the port accepts connections.
Wrong host or port for the CI network
The URL points at a host that is not reachable from the job (for example a Docker-network name when the service is on localhost, or vice versa).
How to fix it
Wait for the DB with a health check
Declare a health check on the service so the job blocks until Postgres accepts connections.
services:
postgres:
image: postgres:16
env:
POSTGRES_PASSWORD: postgres
ports: ['5432:5432']
options: >-
--health-cmd "pg_isready -U postgres"
--health-interval 5s --health-timeout 5s --health-retries 10Prefer Testcontainers for a self-managed DB
Let Testcontainers start the DB and inject a ready URL, removing the readiness race entirely.
@Container
static PostgreSQLContainer<?> db = new PostgreSQLContainer<>("postgres:16");How to prevent it
- Gate the DB service with a health check before the test step runs.
- Match the JDBC host to how the service is exposed (localhost vs network alias).
- Use Testcontainers so the URL is only injected once the DB is accepting connections.