java runtime_error ai_generated true

java.sql.SQLException: Connection refused

ID: java/jdbc-connection-refused

Also available as: JSON · Markdown
85%Fix Rate
88%Confidence
90Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
17 active

Root Cause

JDBC Connection refused occurs when the Java application cannot establish a TCP connection to the database server. The database may not be running, the host/port may be wrong, firewall rules may block the connection, or the JDBC URL may be malformed.

generic

Workarounds

  1. 90% success Verify the database server is running and accessible on the expected host:port
    1. Check if the database process is running: 'systemctl status postgresql' or 'docker ps' for containerized databases. 2. Verify the port is open: 'ss -tlnp | grep 5432' (or your database port). 3. Test TCP connectivity from the application host: 'nc -zv db-host 5432'. 4. Check firewall rules: 'iptables -L' or cloud security group settings. 5. For Docker: ensure the database container is on the same network and the port is exposed.
  2. 85% success Validate the JDBC URL format and connection properties against the database driver documentation
    1. Verify JDBC URL format: jdbc:postgresql://hostname:5432/dbname (PostgreSQL), jdbc:mysql://hostname:3306/dbname (MySQL). 2. Check for typos in hostname, port, and database name. 3. For Docker Compose: use the service name as hostname, not 'localhost'. 4. For Spring Boot: verify spring.datasource.url, spring.datasource.username, spring.datasource.password in application.properties. 5. Ensure the JDBC driver JAR is on the classpath (add the dependency to pom.xml/build.gradle).

Dead Ends

Common approaches that don't work:

  1. Increasing connection timeout to wait longer for the database to respond 85% fail

    If the connection is refused (TCP RST or no route), the failure is immediate — the database is not listening on that host:port. Increasing timeout only helps with slow responses, not with refused connections. A 'Connection refused' means the port is not open, and no amount of waiting will change that.

  2. Switching JDBC drivers without verifying the database is actually reachable 90% fail

    Connection refused is a network-level error, not a driver issue. Switching from MySQL Connector/J to MariaDB Connector or from PostgreSQL JDBC to pgjdbc-ng will not help if the database server is not running or the network path is blocked.

Error Chain

Leads to:
Preceded by:
Frequently confused with: