“No address associated with hostname” is a resolution result, not proof that /etc/hosts is missing one line. The name may not exist, may exist without the requested IPv4/IPv6 record, may rely on a missing search suffix, or may be looked up through different NSS sources inside a container or service.
Quick diagnostic path
name='new-hostname'
printf 'Static hostname: '; hostnamectl --static 2>/dev/null || hostname
getent ahosts "$name"
getent hosts "$name"
awk '/^[[:space:]]*hosts:/{print}' /etc/nsswitch.confWhat these checks establish
nameis a shell variable for this example; replace it with the exact failing name, preserving dots and spelling.getent ahostscallsgetaddrinfo()with an unspecified family on glibc systems, closely matching many applications and following NSS configuration.getent hostsuses the hosts database but has different family/API behavior; compare it rather than treating the two commands as synonyms.The
hosts:line shows lookup sources and order—commonly files, systemd resolve, DNS, mDNS, myhostname, LDAP, or other installed NSS modules.A nonzero result reproduces resolution failure; it does not identify which source or policy caused it. Continue with the branch that matches the name.
What getaddrinfo is doing
application calls getaddrinfo(name, service, hints)
│
▼
/etc/nsswitch.conf → hosts: source order
│ │ │ │
▼ ▼ ▼ ▼
/etc/hosts nss-resolve DNS mDNS/LDAP/etc.
│ │ │ │
└──────────┴──────────┴──────────┘
│ filter by requested family/socket flags
▼
zero or more IPv4/IPv6 socket addressesA simplified glibc/NSS path; exact modules and stop conditions come from the host configuration.
Why error strings vary
getaddrinfo()returns an EAI status code, which an application translates withgai_strerror()or its runtime wrapper.EAI_AGAINsignals temporary resolution failure;EAI_FAILis non-recoverable;EAI_ADDRFAMILYmeans no address in the requested family.glibc documents
EAI_NODATAas a known name with no addresses, while modern interfaces can surface related cases asEAI_NONAME; languages and libraries phrase them differently.Always capture the exact name, family/flags, runtime, host/container, time, and original exception—not only the English message.
Reproduce the application request precisely
#!/usr/bin/env python3
import socket
import sys
name = sys.argv[1]
for family, label in ((socket.AF_UNSPEC, "any"),
(socket.AF_INET, "IPv4"),
(socket.AF_INET6, "IPv6")):
try:
rows = socket.getaddrinfo(name, None, family, socket.SOCK_STREAM)
addresses = sorted({row[4][0] for row in rows})
print(f"{label}: {addresses}")
except socket.gaierror as error:
print(f"{label}: errno={error.errno} message={error.strerror}")Python exposes the address family and socket-type choices passed to the operating-system resolver.
What the probe reveals
AF_UNSPECpermits both IPv4 and IPv6;AF_INETandAF_INET6isolate family-specific failures.SOCK_STREAMasks for stream-compatible results, matching TCP clients more closely than a generic name-only lookup.getaddrinfocan return multiple addresses. Applications should normally try appropriate results rather than assuming the first is permanent.The script uses the current process namespace, NSS libraries, resolver configuration, search domains, and environment. Run it where the failing service actually runs.
A successful lookup does not prove a port is reachable or a service/TLS identity is correct; it proves only that usable socket addresses were returned.
python3 resolve_name.py new-hostname
python3 resolve_name.py new-hostname.example.comCompare short and fully qualified names
A single-label name can depend on configured search domains, LLMNR, mDNS, corporate NSS, or
/etc/hosts.An FQDN with the correct DNS suffix avoids search-list ambiguity, though the trailing-dot absolute form may matter in low-level DNS diagnostics.
If only the short name fails, fix caller configuration or the intended search domain instead of creating a global-looking static alias.
If only one address family fails, confirm whether the application wrongly requires IPv4/IPv6 or the authoritative name lacks the corresponding A/AAAA record.
Branch A: the machine cannot resolve its own hostname
Separate IPv4 and IPv6 results
getent ahostsv4 service.example.com
getent ahostsv6 service.example.com
getent ahosts service.example.comHow to interpret the family checks
ahostsv4constrains the lookup to IPv4-compatible results;ahostsv6isolates IPv6 results.An empty family-specific result can explain why an application constrained to
AF_INETorAF_INET6fails while an unconstrained lookup succeeds.Do not add a fabricated A or AAAA record to make both commands succeed. Confirm the service’s supported address families with its owner.
The unconstrained
ahostsresult is useful for comparison, but the application’s actual family, flags, and runtime remain authoritative.
Some commands resolve the local static hostname to determine canonical identity or bind/report an address. A hostname change can leave DNS, cloud-init, configuration management, /etc/hostname, and /etc/hosts inconsistent. First decide whether the local name should be resolved by authoritative DNS, an NSS myhostname module, or a deliberate static entry.
hostnamectl status 2>/dev/null || true
hostname
getent ahosts "$(hostname)"
getent ahosts localhost
ip -brief addressLocal-hostname takeaways
hostnamereports the kernel hostname; it does not prove DNS registration or an address mapping.hostname --fqdnitself performs resolution and can fail, so do not use it as the only source of truth while diagnosing resolution.localhostshould resolve to loopback independently of the machine’s network hostname.ip -brief addressshows assigned interface addresses but does not tell you which one should be published for a multihomed, mobile, cloud, or container host.Use an organization/cloud hostname registration mechanism for shared identity; a local hosts entry affects only that resolver namespace.
Branch B: a remote or service hostname fails
Verify spelling, Unicode/punycode handling, dots, whitespace, environment-variable expansion, and configuration quoting.
Identify whether the name is public DNS, private DNS, Kubernetes/service discovery, mDNS
.local, a corporate single-label name, or a static lab alias.Run diagnostics from the application’s host/container/network namespace; the administrator laptop may use different DNS and search domains.
Check the authoritative record, delegation, split-horizon view, VPN/VPC resolver path, DNSSEC policy, TTL, and A/AAAA family required.
Do not place a load-balanced/service-discovery name in
/etc/hosts; it freezes one address and bypasses health/rotation logic.
Compare NSS resolution with direct DNS
name='service.example.com'
getent ahosts "$name"
command -v resolvectl >/dev/null && resolvectl query "$name"
command -v dig >/dev/null && dig +noall +answer A "$name"
command -v dig >/dev/null && dig +noall +answer AAAA "$name"Do not confuse these tools
getentfollows the system NSS path used by many glibc applications, including non-DNS sources and NSS stop rules.resolvectl queryuses systemd-resolved and reports protocol/interface/source details on systems that run it.digsends DNS queries according to resolver settings but bypasses/etc/hostsand most NSS modules.If
digsucceeds andgetentfails, inspect NSS order/actions, nss-resolve/systemd-resolved integration, address-family flags, and application namespace.If
/etc/hostsmakesgetentsucceed whiledigstill fails, that is expected: a hosts entry is not a DNS record.
Inspect resolver and NSS configuration
grep -E '^[[:space:]]*hosts:' /etc/nsswitch.conf
ls -l /etc/resolv.conf
sed -n '/^[[:space:]]*(nameserver|search|domain|options)[[:space:]]/p' /etc/resolv.conf
command -v resolvectl >/dev/null && resolvectl statusConfiguration takeaways
NSS source order and bracketed result actions decide whether lookup continues after success, not-found, unavailable, or try-again results. Do not copy a
hosts:line from another distribution blindly./etc/resolv.confcan be generated by NetworkManager, systemd-resolved, DHCP, resolvconf, cloud tooling, a VPN, or a container runtime. Inspect its symlink/owner before editing.A loopback nameserver such as
127.0.0.53can be a local stub, not the upstream DNS address;resolvectl statusshows per-link servers/domains.Search lists expand single-label/relative names and can produce surprising cross-network answers. Prefer explicit FQDNs for service configuration.
Nameserver reachability, UDP/TCP 53, EDNS, DNSSEC, VPN route, and firewall failures require network evidence; replacing the configured file may be temporary or harmful.
Use /etc/hosts only for an intentional static mapping
127.0.0.1 localhost
127.0.1.1 new-hostname.example.test new-hostname
# Remote lab host with a deliberately static managed address:
192.0.2.25 build-node.example.test build-nodeExample syntax only—use an address and names you authoritatively control.
Hosts-file rules
Each line starts with an IPv4/IPv6 address, followed by the canonical hostname and optional aliases separated by whitespace.
192.0.2.25and.example.testare documentation examples; replace them only with an authorized real mapping.127.0.1.1is a Debian/Ubuntu convention for resolving a local hostname without assigning a routable address; it is not a universal Linux rule and must not advertise reachability to other machines.Avoid duplicate/conflicting entries. Depending on NSS/library behavior, ordering can make failures confusing.
A hosts entry cannot express ports, DNS TTL, health checks, SRV/MX semantics, load balancing, or automatic address changes.
Edit and verify the hosts file safely
sudo cp --preserve=mode,ownership,timestamps /etc/hosts /etc/hosts.before-hostname-fix
sudoedit /etc/hosts
getent ahosts new-hostname
getent ahosts new-hostname.example.testRisk level: caution. Review the command before running it.
Change-management takeaways
The backup is local and may contain internal host inventory. Protect it and remove it through normal retention after verification.
sudoeditedits a temporary user-owned copy and installs it with privilege, reducing the need to run a full editor as root.Preserve localhost and IPv6 loopback mappings unless your distribution/network design explicitly says otherwise.
Validate the exact short and FQDN forms the application uses, then test the actual service—not only resolution.
Configuration management, images, containers, and orchestration can overwrite
/etc/hosts; put durable mappings in their source of truth.
systemd-resolved diagnostics
resolvectl status
resolvectl query service.example.com
resolvectl statistics
journalctl -u systemd-resolved --since "10 minutes ago" --no-pagerRead per-link DNS state
statusshows global and per-interface DNS servers, routing/search domains, default-route selection, LLMNR, mDNS, and DNSSEC modes.A VPN can route only selected DNS domains to one interface; the same name may legitimately answer differently before and after connection.
statisticssummarizes cache/validation activity, not a packet-by-packet proof of one query.Resolver logs can contain internal hostnames and network details. Redact before sharing.
Do not restart/disable systemd-resolved merely because it appears in the path; prove the failing scope and owning network manager first.
Flush caches only after fixing the source
sudo resolvectl flush-caches
resolvectl query service.example.comCache takeaways
Flushing removes systemd-resolved’s local resource-record cache; it does not change authoritative DNS,
/etc/hosts, NSS order, search domains, or another cache.Applications, browsers, runtimes, containers, nscd/dnsmasq, proxies, and upstream resolvers may cache independently.
A temporary success after flushing can expose stale/negative cache or changing upstream answers; capture TTL and resolver evidence instead of adding periodic flush jobs.
sudois needed for the cache mutation, not for the follow-up query.
Containers, Kubernetes and chroots
A container has its own
/etc/hosts,/etc/resolv.conf, search domains, and possibly different NSS libraries. Rungetentor the application probe inside it.Docker/Podman generate hosts/resolver files; edit Compose/runtime/network configuration rather than an ephemeral container file.
Kubernetes service search names depend on namespace and cluster domain; test the FQDN and inspect Pod DNS policy/config plus CoreDNS health.
A minimal image may lack
getent,dig,ping, CA certificates, or NSS modules; absence of a debug tool is not proof that the application resolver is broken.glibc and musl can differ in resolver/NSS behavior. Record the base image and C library when results differ between host and container.
Why ping is a weak verification
ping namefirst resolves a name, then sends ICMP. Resolution can succeed while ICMP is blocked.A ping reply proves one address answers ICMP; it does not prove the intended TCP/UDP service, port, TLS certificate, HTTP virtual host, or application health.
Ping output may choose IPv4 or IPv6 differently from the application. Use family-specific lookup and service probes.
Verify resolution with
getent/the application API, then verify the intended endpoint with an appropriate authorized client such ascurl,nc, database tooling, or a health check.
Verify the service after resolution
curl --connect-timeout 5 --verbose https://service.example.com/healthWhat this final check proves—and what it does not
Replace the documentation hostname and path with an endpoint you are authorized to test.
--connect-timeout 5limits connection establishment time; it is not a total request deadline. Add an appropriate--max-timefor automation.Verbose output separates name resolution, address selection, TCP connection, TLS negotiation, and HTTP response stages. Avoid publishing logs that contain tokens, cookies, internal names, or addresses.
An HTTP health response verifies more than
ping, but only for that URL, protocol, network namespace, address selection, and moment in time.
Symptom-to-cause map
Short name fails, FQDN works: missing/wrong search domain, single-label policy, or caller should use FQDN.
A exists but IPv6-only request fails: no AAAA record or application family constraint; fix the record/requirement, not an unrelated IPv4 hosts entry.
dig works, getent fails: NSS/resolved/module/order/action or process namespace problem.
Host works, container fails: generated container DNS/hosts, network, search domain, libc/NSS, or orchestration DNS problem.
Only local hostname fails: hostname registration,
/etc/hosts, myhostname NSS, cloud-init/configuration drift, or inappropriate canonical-name assumption.EAI_AGAIN intermittently: DNS reachability/server load/timeout/temporary failure, not a permanent static mapping invitation.
Works after VPN connects: split DNS/search route is required; configure dependency/readiness and avoid leaking private queries to public resolvers.
Old address persists: identify which cache or static source supplies it and honor TTL/change control.
Production verification checklist
Capture the exact error, requested name, family, time, process/container, node, network/VPN state, and resolver configuration.
Reproduce with the same runtime
getaddrinfocall and withgetent ahostsin the same namespace.Classify the name as local, public DNS, private DNS, service discovery, mDNS, or intentional static alias.
Compare short/FQDN and IPv4/IPv6 results; inspect NSS order and direct DNS/resolved evidence.
Fix the authoritative source or caller configuration, preserving dynamic service behavior.
Retest resolution and the real application protocol from every relevant namespace/network.
Remove temporary overrides/debug files and encode the durable configuration in DNS, DHCP, cloud, image, or orchestration source control.
Related Linux networking guides
Change local identity with setting the Ubuntu hostname.
Inspect paths using Linux route and IP commands.
Diagnose DNS using dig, host and nslookup examples.
Primary references
The Linux man-pages project documents `getaddrinfo(3)` return codes and family-independent resolution.
`getent(1)` documents NSS database queries and
ahostsuse ofgetaddrinfo.`nsswitch.conf(5)` defines name-service source order and result actions.
`hosts(5)` defines static hosts-file format.
The systemd project documents `resolvectl` query, status, monitoring, and cache controls.
Comments and corrections