BackendBench
Coffee

Home โ€บ Java exceptions โ€บ ConnectException

Checked exception ยท java.net

ConnectException: causes and fixes

The TCP connection was refused or could not be made: nothing is listening, or a firewall rejected it.

What it looks like

java.net.ConnectException: Connection refused

Extends SocketException in java.net.

What it means

"Connection refused" means the host answered and said no: the machine is reachable, but no process is listening on that port (or something actively rejected the connection). That is different from a timeout, where nothing answers at all. It is the standard error when a service is not started yet, listens on a different port or interface, or when a container tries to reach localhost expecting the host.

Common causes

How to fix it

  1. Check the service is up and the port is open: curl, nc -zv host port or ss -ltn.
  2. Use the service name in Compose or Kubernetes instead of localhost.
  3. Bind servers to 0.0.0.0 when other hosts must reach them.
  4. Add readiness checks or startup retries so dependants wait for the dependency.

Broken and fixed

fails
spring.datasource.url=jdbc:postgresql://localhost:5432/app # inside a container
works
spring.datasource.url=jdbc:postgresql://db:5432/app # the Compose service name

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

Spring Boot apps in Docker Compose often start before the database accepts connections. Use depends_on with a healthcheck or retry the connection.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is ConnectException a checked or unchecked exception?

ConnectException is a checked exception (it extends SocketException), so the compiler forces you to catch it or declare it with throws.

Which package is ConnectException in?

It lives in java.net, so the import is import java.net.ConnectException;.

What is the first thing to check when I see ConnectException?

Read the message and the first stack trace line in your own code. The usual causes are: The target service is not running, has not finished starting, or crashed; and Wrong host or port in the configuration.

Related exceptions

More tools you might need