BackendBench
Coffee

Home โ€บ Java exceptions โ€บ UnknownHostException

Checked exception ยท java.net

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 known

Extends 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

How to fix it

  1. Try nslookup name or dig name from the same machine or pod that runs the app.
  2. Print the effective host from configuration to catch placeholders and whitespace.
  3. In Kubernetes use the full service name (svc.namespace.svc.cluster.local) across namespaces.
  4. Set proxy options (-Dhttps.proxyHost) or use the JVM-wide proxy configuration when required.

Broken and fixed

fails
client.get("https://api.exmaple.com/v1"); // typo in the domain
works
client.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.

Related exceptions

More tools you might need