Fix PSQLException Connection Refused on Port 5432 Errors
Fix the PostgreSQL JDBC connection refused error by checking that the server runs and listens, the host and port are right, and Docker networking is correct.

The application starts, tries to open its first database connection and stops with this:
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.
Caused by: java.net.ConnectException: Connection refusedThe second line is the one that matters. Connection refused is a TCP-level answer: the machine at that address replied that no process is listening on that port. The password is not wrong, the database does not exist and the driver is fine, since nothing got far enough to ask. That narrows the search to five places, and each one can be checked with a single command from the same machine or container as the application. Examples use PostgreSQL 17, the PostgreSQL JDBC driver 42.7 and Spring Boot 4.
Check 1: is the server running and listening?
Start with the server itself. pg_isready ships with PostgreSQL and tests exactly this:
pg_isready -h localhost -p 5432localhost:5432 - no responseno response means nothing is accepting connections. A healthy server prints accepting connections. If it fails, find out whether the process exists and what it listens on:
# Linux
systemctl status postgresql
ss -ltnp | grep 5432
# macOS with Homebrew
brew services list | grep postgres
lsof -iTCP:5432 -sTCP:LISTENLISTEN 0 244 127.0.0.1:5432 0.0.0.0:* users:(("postgres",pid=1432,fd=6))If there is no line, the server is stopped or crashed. Start it, and read its log if it refuses; the usual reasons are a stale postmaster.pid after a hard shutdown, a port already used by another instance, or a full disk. In a Docker setup, check the container is up and healthy, not just created:
docker ps --filter name=postgres --format '{{.Names}} {{.Status}}'
docker logs --tail 20 postgrespostgres Up 12 seconds (healthy)A container that is Up but still initializing a fresh data directory refuses connections for several seconds. An application that starts at the same moment hits exactly this error. The cure is a startup order that waits for health, covered below.
Check 2: are the host and port in the URL right?
Compare what the application uses with what the server offers. A JDBC URL has a fixed shape:
spring.datasource.url=jdbc:postgresql://localhost:5432/shop
spring.datasource.username=shop
spring.datasource.password=change-meThe error message prints the host and port the driver used, so read them. Common slips: the port is the default 5432 but the server was installed on 5433 because another version already held 5432; the URL points at a development host from a copied profile; an environment variable such as SPRING_DATASOURCE_URL overrides the file, which is why the effective value matters. Print it at startup or read /actuator/env. How environment variables map to properties is in importing config from environment variables, and the full JDBC URL syntax is in the PostgreSQL JDBC documentation.
Test the same address without Java in the way, which separates the driver from the network:
nc -vz localhost 5432nc: connectx to localhost port 5432 (tcp) failed: Connection refusedIf nc is refused, no Java setting will help. For a first working connection from scratch, see the walkthrough in connecting to a database step by step with JDBC.
Check 3: Docker and localhost
Inside a container, localhost means that container. An application running in Docker that connects to localhost:5432 is looking for PostgreSQL inside its own container, where there is none, and gets Connection refused even though the database is running fine on the host or in a neighbor container.
services:
db:
image: postgres:17
environment:
POSTGRES_USER: shop
POSTGRES_PASSWORD: change-me
POSTGRES_DB: shop
healthcheck:
test: ["CMD-SHELL", "pg_isready -U shop -d shop"]
interval: 5s
timeout: 3s
retries: 10
app:
image: registry.example.test/shop:1.4.2
environment:
SPRING_DATASOURCE_URL: jdbc:postgresql://db:5432/shop
depends_on:
db:
condition: service_healthyTwo changes matter. The host in the URL is the service name db, which Compose resolves on the shared network. And depends_on with service_healthy makes app wait until the health check passes, which removes the startup race from Check 1. When the database runs on the host machine and the application in a container, use host.docker.internal on Docker Desktop, or add --add-host=host.docker.internal:host-gateway on Linux.
The mapping direction is easy to confuse. ports: ["5433:5432"] exposes the container's 5432 on the host's 5433. From the host use 5433; from another container on the same network use db:5432.
Check 4: the server only listens on the loopback
PostgreSQL's listen_addresses defaults to localhost. That is fine for a client on the same machine and a guaranteed refusal for any other. Look at the output of the ss command above: 127.0.0.1:5432 accepts only local connections, while 0.0.0.0:5432 or *:5432 accepts from the network.
listen_addresses = '*'
port = 5432Changing it requires a restart, not a reload. Opening the listener is not enough, because PostgreSQL also needs a matching rule in pg_hba.conf for the client's address:
host shop shop 10.0.0.0/16 scram-sha-256Without a matching pg_hba.conf line the error changes to FATAL: no pg_hba.conf entry for host ..., which is progress: the TCP connection worked and the next layer is what refused. A refused connection never reaches that file. Keep listen_addresses as narrow as the deployment allows; * on a public interface with a weak rule is how databases get exposed. The parameter is documented in the PostgreSQL connection settings.
Check 5: a firewall or security group
Between two machines, something can drop or reject the traffic. The difference shows in the symptom. A reject sends back a refusal immediately, so you get Connection refused in milliseconds. A silent drop gives no answer, and the client waits until the connect timeout, which surfaces as a different message, The connection attempt failed caused by SocketTimeoutException: connect timed out. So an instant refusal points to the host's own firewall or to no listener, and a long wait points to a network-level filter such as a cloud security group.
# on the database host
sudo ufw status
sudo iptables -L INPUT -n | grep 5432Open the port to the application's subnet only, never to the world. In a cloud, add an inbound rule on the database's security group that allows port 5432 from the application's security group.
Once it connects, what next
A connected application can still fail on the next layer: an exhausted pool shows as a different error, described in connection is not available, request timed out, and a first project that wires JPA to this database is in a Hibernate tutorial for beginners. Guard against the startup race for good with a retry on the first connection, or with the database health check above.
Where this does not apply
If the message says FATAL: password authentication failed, database "shop" does not exist or no pg_hba.conf entry, you are past the refusal and the network is fine; fix credentials, the database name or pg_hba.conf. If you reach a managed database such as Amazon RDS through a proxy or a pooler, the port may not be 5432, and the endpoint must come from the service console. A connection timeout, rather than a refusal, belongs to Check 5 and to routing, not to the checks before it.


