“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

Terminalbash
name='new-hostname'
printf 'Static hostname: '; hostnamectl --static 2>/dev/null || hostname
getent ahosts "$name"
getent hosts "$name"
awk '/^[[:space:]]*hosts:/{print}' /etc/nsswitch.conf

What these checks establish

  • name is a shell variable for this example; replace it with the exact failing name, preserving dots and spelling.

  • getent ahosts calls getaddrinfo() with an unspecified family on glibc systems, closely matching many applications and following NSS configuration.

  • getent hosts uses 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

linux-name-resolution-path.txttext
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 addresses

A 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 with gai_strerror() or its runtime wrapper.

  • EAI_AGAIN signals temporary resolution failure; EAI_FAIL is non-recoverable; EAI_ADDRFAMILY means no address in the requested family.

  • glibc documents EAI_NODATA as a known name with no addresses, while modern interfaces can surface related cases as EAI_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

resolve_name.pypython
#!/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_UNSPEC permits both IPv4 and IPv6; AF_INET and AF_INET6 isolate family-specific failures.

  • SOCK_STREAM asks for stream-compatible results, matching TCP clients more closely than a generic name-only lookup.

  • getaddrinfo can 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.

Terminalbash
python3 resolve_name.py new-hostname
python3 resolve_name.py new-hostname.example.com

Compare 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

Terminalbash
getent ahostsv4 service.example.com
getent ahostsv6 service.example.com
getent ahosts service.example.com

How to interpret the family checks

  • ahostsv4 constrains the lookup to IPv4-compatible results; ahostsv6 isolates IPv6 results.

  • An empty family-specific result can explain why an application constrained to AF_INET or AF_INET6 fails 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 ahosts result 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.

Terminalbash
hostnamectl status 2>/dev/null || true
hostname
getent ahosts "$(hostname)"
getent ahosts localhost
ip -brief address

Local-hostname takeaways

  • hostname reports the kernel hostname; it does not prove DNS registration or an address mapping.

  • hostname --fqdn itself performs resolution and can fail, so do not use it as the only source of truth while diagnosing resolution.

  • localhost should resolve to loopback independently of the machine’s network hostname.

  • ip -brief address shows 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

Terminalbash
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

  • getent follows the system NSS path used by many glibc applications, including non-DNS sources and NSS stop rules.

  • resolvectl query uses systemd-resolved and reports protocol/interface/source details on systems that run it.

  • dig sends DNS queries according to resolver settings but bypasses /etc/hosts and most NSS modules.

  • If dig succeeds and getent fails, inspect NSS order/actions, nss-resolve/systemd-resolved integration, address-family flags, and application namespace.

  • If /etc/hosts makes getent succeed while dig still fails, that is expected: a hosts entry is not a DNS record.

Inspect resolver and NSS configuration

Terminalbash
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 status

Configuration 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.conf can 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.53 can be a local stub, not the upstream DNS address; resolvectl status shows 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

/etc/hoststext
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-node

Example 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.25 and .example.test are documentation examples; replace them only with an authorized real mapping.

  • 127.0.1.1 is 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

Terminalbash
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.test

Risk 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.

  • sudoedit edits 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

Terminalbash
resolvectl status
resolvectl query service.example.com
resolvectl statistics
journalctl -u systemd-resolved --since "10 minutes ago" --no-pager
  • status shows 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.

  • statistics summarizes 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

Terminalbash
sudo resolvectl flush-caches
resolvectl query service.example.com

Cache 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.

  • sudo is 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. Run getent or 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 name first 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 as curl, nc, database tooling, or a health check.

Verify the service after resolution

Terminalbash
curl --connect-timeout 5 --verbose https://service.example.com/health

What 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 5 limits connection establishment time; it is not a total request deadline. Add an appropriate --max-time for 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

  1. Capture the exact error, requested name, family, time, process/container, node, network/VPN state, and resolver configuration.

  2. Reproduce with the same runtime getaddrinfo call and with getent ahosts in the same namespace.

  3. Classify the name as local, public DNS, private DNS, service discovery, mDNS, or intentional static alias.

  4. Compare short/FQDN and IPv4/IPv6 results; inspect NSS order and direct DNS/resolved evidence.

  5. Fix the authoritative source or caller configuration, preserving dynamic service behavior.

  6. Retest resolution and the real application protocol from every relevant namespace/network.

  7. Remove temporary overrides/debug files and encode the durable configuration in DNS, DHCP, cloud, image, or orchestration source control.

Primary references

  • The Linux man-pages project documents `getaddrinfo(3)` return codes and family-independent resolution.

  • `getent(1)` documents NSS database queries and ahosts use of getaddrinfo.

  • `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.