Home โบ Java exceptions โบ UnknownHostException
UnknownHostException: causes and fixes
A host name could not be resolved to an IP address.
What it looks like
java.net.UnknownHostException: api.example.com: Name or service not knownExtends IOException in java.net.
What it means
DNS failed to resolve the name. The message contains the host that failed, so a typo is easy to spot. When the name is right, the cause is usually the environment: no network, a DNS server that cannot be reached, a name that only resolves on a VPN or inside the cluster, or a container with no DNS configuration. It is thrown before any connection is attempted.
Common causes
- A typo in the host name, or a placeholder that was never replaced (
${host}or a trailing space). - No internet or DNS access from the container or CI runner.
- An internal name that only resolves on a VPN or in a different Kubernetes namespace.
- Corporate proxy settings that are not applied to the JVM.
How to fix it
- Try
nslookup nameordig namefrom the same machine or pod that runs the app. - Print the effective host from configuration to catch placeholders and whitespace.
- In Kubernetes use the full service name (
svc.namespace.svc.cluster.local) across namespaces. - Set proxy options (
-Dhttps.proxyHost) or use the JVM-wide proxy configuration when required.
Broken and fixed
client.get("https://api.exmaple.com/v1"); // typo in the domainclient.get(config.apiBaseUrl() + "/v1"); // from validated configuration๐ Unravel the failing code ๐ Unravel the fix
In Spring and enterprise code
The JVM caches successful DNS lookups (and failed ones briefly). In dynamic environments review networkaddress.cache.ttl so IP changes are picked up.
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 UnknownHostException a checked or unchecked exception?
UnknownHostException is a checked exception (it extends IOException), so the compiler forces you to catch it or declare it with throws.
Which package is UnknownHostException in?
It lives in java.net, so the import is import java.net.UnknownHostException;.
What is the first thing to check when I see UnknownHostException?
Read the message and the first stack trace line in your own code. The usual causes are: A typo in the host name, or a placeholder that was never replaced (${host} or a trailing space); and No internet or DNS access from the container or CI runner.