Home โบ Java exceptions โบ ConnectException
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 refusedExtends 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
- The target service is not running, has not finished starting, or crashed.
- Wrong host or port in the configuration.
- In Docker or Kubernetes,
localhostrefers to the container itself, not the database or another service. - The service listens only on 127.0.0.1 but is reached from another host.
How to fix it
- Check the service is up and the port is open:
curl,nc -zv host portorss -ltn. - Use the service name in Compose or Kubernetes instead of localhost.
- Bind servers to
0.0.0.0when other hosts must reach them. - Add readiness checks or startup retries so dependants wait for the dependency.
Broken and fixed
spring.datasource.url=jdbc:postgresql://localhost:5432/app # inside a containerspring.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.