You type sudo. You wait. The cursor blinks like it’s thinking about a career change.
Then, finally, a password prompt appears—seconds late, every time.
On Ubuntu 24.04 this is still a common “works on my laptop” bug that shows up in the worst places:
bastion hosts, CI runners, jump boxes, and freshly provisioned cloud VMs with just enough DNS weirdness to waste your day.
The good news: most slow sudo delays boil down to hostname and DNS resolution, and you can fix them with boring, deterministic steps.
What “slow sudo” really is (and what it isn’t)
“Slow sudo” is usually not your disk, not your CPU, and not a haunted PAM module summoning demons.
It’s typically a blocking name resolution call that happens before sudo prints the password prompt.
That call can be forward DNS, reverse DNS, mDNS, LDAP/SSSD name services, or even a resolver that’s misconfigured and timing out.
The reason it feels like sudo is slow is that the human sees only one thing: the password prompt.
Under the hood, sudo is doing setup work (policy lookup, host identification, auditing, logging).
If any dependency blocks—especially name resolution—you sit there.
What it looks like
- Delay occurs before password prompt appears (classic).
- Delay is consistent: ~1–5 seconds, often exactly matching DNS timeout/retry patterns.
- Delay disappears when you disconnect VPN / leave corporate network / switch Wi‑Fi.
- Delay is present on the console and SSH, not just one terminal emulator.
What it is not (most of the time)
- Not your shell config. Shell prompts happen before you type
sudo. - Not your disk being slow.
sudoreads small files. Your NVMe is not the bottleneck here. - Not a “need more RAM” problem. The delay is wall-clock, not CPU time.
Joke #1: DNS is the “it was working yesterday” department of IT. It’s also the “it’ll work tomorrow” department, which is less comforting.
Fast diagnosis playbook
You want the fastest path to “what is it blocking on?” without yak-shaving.
Here’s the playbook I use on production hosts where patience is a liability.
First: measure the delay and confirm it’s name resolution
- Time
sudoand reproduce twice to confirm consistency. - Run
straceonsudoand look forconnect()/sendto()to DNS orgetaddrinfo()calls. - Test local hostname resolution via
getent(forward and reverse) because that’s what libc/NSS actually uses.
Second: identify which resolver path is being used
- Check
/etc/nsswitch.conffor thehosts:line. This dictates lookup order (files,dns,mdns4_minimal,resolve). - Inspect
resolvectl status(systemd-resolved) or/etc/resolv.confto see where queries go. - If on corporate systems, check SSSD/LDAP/AD integration because it can hook into host/user lookups.
Third: fix the simplest thing that guarantees a fast path
- Ensure your hostname is mapped in
/etc/hoststo a loopback entry (127.0.1.1or127.0.0.1) with both short name and FQDN if needed. - Remove “cute” resolver options that increase timeout (bad search domains, broken nameservers).
- Only then, tweak sudo/PAM/logging if you have a proven reason.
Why sudo touches DNS/hostname at all
sudo is more than “run command as root.” It’s a policy engine with audit trails.
It needs to decide whether you may run this command here.
“Here” means the host identity. “You” means a username and groups. “Audit” means logs that often include hostnames.
The usual culprits for hostname/DNS-induced delay
-
Hostname resolution for logging and policy.
Many environments want logs with names, not raw IPs. That can trigger reverse lookup. -
NSS (Name Service Switch) order.
If yourhosts:line tries mDNS, WINS, LDAP, or resolver daemons before checkingfiles,
you can pay for it on every call. -
systemd-resolved or upstream DNS timeouts.
Resolver timeouts are often a few seconds—exactly the delay you see. -
FQDN mismatch.
A machine namedweb-01whose DNS says it’sweb-01.corp.examplebut/etc/hostsdisagrees
can send lookups down slow paths. -
SSSD / AD integration.
If you’re using domain users, SSSD can add latency when it tries to contact controllers—even for “local” actions.
The posture I recommend: treat host identity and name service like dependencies.
Dependencies fail in weird ways. Make the fast path local, deterministic, and boring.
Quote (paraphrased idea) from Werner Vogels (Amazon CTO): Everything fails all the time; design assuming components will break.
Facts & historical context you can use in arguments
These aren’t trivia for trivia’s sake. They explain why modern Ubuntu name resolution can feel like a Rube Goldberg machine
if you approach it like it’s 2009.
- NSS (Name Service Switch) dates back to Solaris and was adopted widely on Linux to control lookup order (files, DNS, LDAP, etc.). Misordering still causes “mystery slowness.”
- Ubuntu historically used
127.0.1.1in/etc/hostsfor the local hostname, especially on systems without a stable IP. It’s odd, but it prevents resolver trips. - systemd-resolved introduced a local stub resolver behavior that changed how
/etc/resolv.confbehaves on many distros. The path “who answers DNS?” became less obvious. - mDNS (multicast DNS) is great for printers and laptops; it’s a liability on servers if it’s ahead of
filesand your network filters multicast weirdly. - Reverse DNS (PTR) is still commonly missing or wrong in internal networks. That’s fine until something blocks on it, like logging/auditing.
- VPN clients often push search domains and nameserver lists that are correct for internal apps but disastrous for latency if the network path is lossy.
- Sudo’s behavior has evolved with security expectations: more auditing, more policy context, more places where a hostname ends up in logs.
- Corporate Windows-era DNS patterns (WINS, split DNS, long search lists) still leak into Linux configs via DHCP and can slow lookups dramatically.
Practical tasks: commands, outputs, and decisions (12+)
Each task includes: a command you can run, an example of what “bad” or “interesting” output looks like,
and what decision you make from it. Don’t skim the decisions—that’s where the money is.
Task 1: Time the symptom like you mean it
cr0x@server:~$ time sudo -n true
real 0m2.312s
user 0m0.008s
sys 0m0.010s
What it means: 2.3 seconds real time, near-zero CPU. That screams “blocked on I/O,” and DNS is I/O.
Decision: Stop guessing about CPU/disk. Move to tracing name service.
Task 2: Confirm it’s before the password prompt (interactive)
cr0x@server:~$ time sudo true
[sudo] password for cr0x:
real 0m2.205s
user 0m0.009s
sys 0m0.012s
What it means: Delay is before password input is accepted (prompt appears late).
Decision: Look at hostname resolution and logging, not PAM password verification.
Task 3: Use strace to catch the blocker (fast and rude)
cr0x@server:~$ sudo strace -f -tt -o /tmp/sudo.trace sudo -n true
sudo: a password is required
cr0x@server:~$ tail -n 25 /tmp/sudo.trace
12:20:01.101234 connect(6, {sa_family=AF_INET, sin_port=htons(53), sin_addr=inet_addr("10.0.0.2")}, 16) = 0
12:20:01.101540 sendto(6, "\252\273\1\0\0\1\0\0\0\0\0\0\6server\4corp\7example\0\0\34\0\1", 36, 0, NULL, 0) = 36
12:20:03.103901 recvfrom(6, 0x7ffd8b2a3f10, 2048, 0, NULL, NULL) = -1 EAGAIN (Resource temporarily unavailable)
12:20:03.104220 close(6) = 0
What it means: A DNS query to 10.0.0.2 timed out after ~2 seconds.
Decision: Fix resolver reachability/order or bypass DNS for local hostname via /etc/hosts.
Task 4: Inspect what hostname sudo thinks it’s on
cr0x@server:~$ hostnamectl
Static hostname: server
Icon name: computer-vm
Chassis: vm
Machine ID: 8cbe2c8a1b3d4f1e9e6c0c4b3c1c9d2a
Boot ID: 2f9c9a1de2bf44a6a3a8c5f5f7e38e0a
Virtualization: kvm
Operating System: Ubuntu 24.04 LTS
Kernel: Linux 6.8.0-31-generic
Architecture: x86-64
What it means: Static hostname is server (short name).
Decision: Ensure server resolves quickly via /etc/hosts. Decide whether you also need an FQDN.
Task 5: Check forward lookup through NSS (not “dig”, not “nslookup”)
cr0x@server:~$ getent hosts $(hostname)
10.22.1.17 server.corp.example server
What it means: NSS returns a DNS-backed address quickly (in this example).
If this command stalls, sudo can stall too.
Decision: If it’s slow, prioritize fixing /etc/hosts or resolver settings.
Task 6: Check reverse lookup for your primary IP
cr0x@server:~$ ip -br addr show scope global
ens3 UP 10.22.1.17/24
cr0x@server:~$ getent hosts 10.22.1.17
10.22.1.17 server
What it means: Reverse lookup returns server.
If it times out, your logging stack or sudo might be triggering PTR lookups.
Decision: If reverse is slow, either fix PTR in DNS (best) or ensure local mapping in /etc/hosts.
Task 7: Check /etc/hosts for the classic missing mapping
cr0x@server:~$ sed -n '1,120p' /etc/hosts
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
What it means: No entry for server. That forces NSS to consult network sources.
Decision: Add a loopback mapping for your hostname to make local resolution instant.
Task 8: Inspect NSS order for host lookups
cr0x@server:~$ grep -E '^\s*hosts:' /etc/nsswitch.conf
hosts: files mdns4_minimal [NOTFOUND=return] dns
What it means: This tries files, then mDNS, then DNS.
On servers, mDNS can be a detour you don’t want.
Decision: If mDNS is causing delays, consider removing or moving it after dns (carefully—see fixes).
Task 9: See whether systemd-resolved is in charge
cr0x@server:~$ resolvectl status
Global
Protocols: -LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
resolv.conf mode: stub
Current DNS Server: 10.0.0.2
DNS Servers: 10.0.0.2 10.0.0.3
DNS Domain: corp.example
What it means: Queries go to 10.0.0.2/10.0.0.3. Stub mode means /etc/resolv.conf points to a local stub.
Decision: Test these DNS servers directly. If they’re unreachable from this host/network, fix DHCP/VPN/resolver config.
Task 10: Validate that DNS servers respond quickly (direct query)
cr0x@server:~$ dig +time=1 +tries=1 @10.0.0.2 $(hostname).corp.example A
; <<>> DiG 9.18.24-0ubuntu0.24.04.1-Ubuntu <<>> +time=1 +tries=1 @10.0.0.2 server.corp.example A
;; global options: +cmd
;; connection timed out; no servers could be reached
What it means: The configured DNS server is not reachable (or filtered).
Decision: Fix the resolver list. Or, if you can’t, short-circuit local hostname via /etc/hosts so sudo doesn’t care.
Task 11: Check /etc/resolv.conf for stub vs direct resolvers
cr0x@server:~$ readlink -f /etc/resolv.conf
/run/systemd/resolve/stub-resolv.conf
What it means: You’re using systemd-resolved’s local stub.
Decision: Don’t “fix” /etc/resolv.conf by hand unless you are intentionally opting out. Fix the upstream config instead.
Task 12: See if SSSD is in the lookup path (common in enterprise)
cr0x@server:~$ systemctl is-active sssd
active
cr0x@server:~$ getent passwd $USER
cr0x:x:1000:1000:cr0x:/home/cr0x:/bin/bash
What it means: SSSD is running. It may influence lookups depending on NSS config.
Decision: If sudo delays correlate with AD/DC reachability, inspect SSSD logs and NSS config; don’t just blame DNS.
Task 13: Detect search domain pain (slow NXDOMAIN walking)
cr0x@server:~$ resolvectl domain
Global: corp.example lab.example dev.example
What it means: Multiple search domains can cause multiple queries per lookup, especially with unqualified names.
Decision: Prefer FQDNs in configs, trim search lists where possible, and ensure your hostname resolves without a search walk.
Task 14: Measure lookup latency through NSS (repeatable)
cr0x@server:~$ /usr/bin/time -f '%e seconds' getent hosts $(hostname) >/dev/null
2.01 seconds
What it means: NSS lookup itself is taking ~2 seconds.
Decision: Fix name resolution first. Sudo is just the messenger getting shot.
Task 15: Prove mDNS is or isn’t involved
cr0x@server:~$ /usr/bin/time -f '%e seconds' getent hosts server.local >/dev/null
1.99 seconds
What it means: .local lookups can trigger mDNS. If this is slow and your hosts: includes mdns, you have a lead.
Decision: On servers, disable mDNS or reorder it unless you have a real requirement for it.
Task 16: Confirm sudo log settings aren’t forcing FQDN weirdness
cr0x@server:~$ sudo -V | sed -n '1,60p'
Sudo version 1.9.15p5
Sudoers policy plugin version 1.9.15p5
Sudoers file grammar version 50
Sudoers I/O plugin version 1.9.15p5
Sudoers audit plugin version 1.9.15p5
Local IP address and netmask pairs:
10.22.1.17 / 255.255.255.0
What it means: You’re seeing local IP enumeration. Sometimes that enumeration triggers reverse lookups depending on environment.
Decision: Keep focus: fix resolution of hostname/IP locally. Don’t cargo-cult sudoers knobs until you’ve measured.
Fix patterns that actually remove the delay
There are a dozen ways to “make it feel better” and two ways to make it actually correct.
The correct ways are: (1) make hostname resolution local and instant, and (2) make upstream DNS reliable and reachable.
Do both when you can. Do (1) when you must.
Fix #1: Put your hostname in /etc/hosts (fast path, nearly always safe)
On Ubuntu, the most common fix is also the least glamorous: ensure the system’s hostname resolves via files
without touching DNS. That means adding a loopback mapping.
What to do (example for hostname server and FQDN server.corp.example):
cr0x@server:~$ sudoedit /etc/hosts
Example content to add (keep existing lines):
cr0x@server:~$ sed -n '1,20p' /etc/hosts
127.0.0.1 localhost
127.0.1.1 server.corp.example server
::1 localhost ip6-localhost ip6-loopback
What it means: The hostname resolves immediately via files. No DNS dependency for local identity.
Decision: If this eliminates the delay, you can schedule DNS hygiene later instead of burning the afternoon.
Opinionated guidance: for a server, I want /etc/hosts to contain the local hostname.
Yes, even if “DNS should be the source of truth.” DNS is a source of truth until it’s a source of paging.
Fix #2: Make sure your hostname and FQDN expectations match
Problems happen when different layers disagree about whether the “real” name is short or fully qualified.
Some environments treat server as “server.corp.example” via search domains; others don’t.
Your job is to make it explicit.
Decide what the hostname should be:
- Short hostname (
server): common for VMs, internal hosts, and when you don’t want renames. - FQDN hostname (
server.corp.example): sometimes required by tooling, certificates, or AD policies.
Set it clearly (if you must change it):
cr0x@server:~$ sudo hostnamectl set-hostname server.corp.example
Decision: Only set FQDN as static hostname if your org needs it. Otherwise keep short hostname and map FQDN in /etc/hosts.
Renaming hosts in production is a fine way to discover everything that assumes names never change.
Fix #3: Fix resolver reachability (stop timing out to dead DNS)
If your configured DNS servers don’t answer, every lookup becomes a timeout lottery.
With systemd-resolved, you often inherit resolvers from DHCP, VPN, or netplan configuration.
Find the active DNS servers:
cr0x@server:~$ resolvectl dns
Global: 10.0.0.2 10.0.0.3
Link 2 (ens3): 10.0.0.2 10.0.0.3
Decision: If those are unreachable from this network segment, fix the network config (DHCP scope, VPN profile, netplan).
Don’t “solve” it by adding random public DNS on a corporate host unless you want split-DNS outages and compliance trouble.
Fix #4: Trim search domains (reduce query multiplication)
Search domains can cause multiple queries for a single name: server becomes server.corp.example,
then server.lab.example, and so on. When resolvers are slow, that multiplies pain.
Decision: Prefer using FQDNs in configs and set the machine’s hostname mapping so it does not depend on search.
If you manage DHCP, keep the search list short and intentional.
Fix #5: Reorder NSS lookups so “files” wins quickly
The hosts: line in /etc/nsswitch.conf decides the lookup order.
For servers, I want files first, DNS second, and mDNS only if there’s a specific reason.
cr0x@server:~$ grep -E '^\s*hosts:' /etc/nsswitch.conf
hosts: files mdns4_minimal [NOTFOUND=return] dns
If mDNS is implicated, a safer server-side pattern is often:
cr0x@server:~$ sudo sed -i 's/^hosts:.*/hosts: files dns/' /etc/nsswitch.conf
Decision: Only do this if you understand the environment. On desktops, removing mDNS can break “it just appears” device discovery.
On servers, it usually removes dead weight.
Fix #6: Handle reverse DNS properly (PTR records or local mapping)
Reverse DNS being wrong is common and survivable—until a security policy or logging path blocks on it.
The clean fix is to create PTR records for server IPs in the authoritative DNS.
The tactical fix is to ensure the server’s own IP reverse-resolves locally via /etc/hosts.
Opinionated guidance: if you operate the DNS zone, do PTRs. It’s not optional hygiene, it’s operational debt with interest.
Fix #7: Beware of “quick fixes” that hide symptoms
You’ll see advice like “disable DNS lookups in sudo” or tweak logging.
Sometimes those changes help. More often they just make your audit trail worse while leaving DNS broken for everything else.
Use them only when you have a measured reason and a change record.
Joke #2: Turning off DNS to fix DNS latency is like removing your speedometer to improve fuel economy. You’ll feel better briefly.
Three corporate mini-stories (anonymized, plausible, technically accurate)
1) The incident caused by a wrong assumption: “Our DNS is always reachable”
A team ran a fleet of Ubuntu VMs across two network zones: app servers in one, shared services (including DNS) in another.
During a security review, firewall rules were tightened. DNS was “allowed,” but only from subnets listed in a spreadsheet that was—how to put this—optimistic.
The first symptom wasn’t an app outage. It was humans complaining in chat that sudo “hangs sometimes.”
The on-call dismissed it as personal laptops and VPN weirdness. Then a routine package update window started, and automation that used sudo began to time out.
That’s when the problem graduated from annoyance to incident.
The wrong assumption: “If SSH works, DNS must work.” SSH worked because IP routes were fine and hosts were pinned in known_hosts.
DNS did not work because the firewall was dropping UDP/53 silently, which translates to “wait for timeout, then retry.”
Fixing the firewall was necessary, but the durable fix was adding local hostname mappings in /etc/hosts via configuration management.
That made identity resolution local, so even if DNS wobbled, administrative actions didn’t.
Post-incident, they also added a health check: getent hosts $(hostname) latency measured and alerted.
Boring metric. Extremely effective.
2) The optimization that backfired: “Let’s add more search domains”
A corporate network team tried to make developer experience smoother by pushing a generous search list via DHCP:
multiple internal domains so people could type short hostnames and have them “just work.”
It looked harmless. It even worked—when DNS was fast.
Then a remote office had intermittent packet loss to the main DNS resolvers.
Each unqualified lookup (like server) became a series of attempts: server.corp, server.lab, server.dev, and so on.
Multiply that by timeouts and retries, and suddenly trivial commands were taking seconds.
Engineers noticed it first in tools that call out to NSS repeatedly: sudo, ssh with GSSAPI attempts,
and monitoring agents doing reverse lookups for tagging.
The network team’s “optimization” had created a latency amplifier.
Rolling back the search list helped, but the real repair was more disciplined naming:
critical systems used FQDNs in configs, and hosts pinned their own name locally.
Short names were still allowed in interactive shells, but production automation stopped depending on search magic.
3) The boring but correct practice that saved the day: standardized /etc/hosts entries
Another company had a strict baseline: every Linux host had an /etc/hosts entry for its own hostname,
managed by configuration management, reviewed like any other change.
People grumbled because it felt redundant with DNS.
During a planned DNS migration, resolvers were swapped and caches flushed.
A handful of zones were slower for a few hours due to propagation and a couple of misconfigured forwarders.
Developers complained that “DNS is slow,” but operational work on servers continued without drama.
The reason: admin workflows didn’t require DNS for local identity.
sudo, local log tagging, and many scripts that used hostname -f didn’t block because the host could answer “who am I?”
from local files instantly.
This didn’t eliminate the DNS issue. It contained it.
That’s the point of boring baselines: they don’t prevent every fire, but they keep the fire from spreading into unrelated rooms.
Common mistakes: symptoms → root cause → fix
1) Symptom: sudo pauses ~2–5 seconds before password prompt
Root cause: DNS servers in resolver config are unreachable; libc waits for timeout.
Fix: Correct DNS server list (DHCP/VPN/netplan), and add hostname mapping in /etc/hosts as a guardrail.
2) Symptom: sudo is fast on one network, slow on another
Root cause: Split DNS/VPN changes resolvers or search domains; queries go to a resolver that’s slow from that location.
Fix: Measure with resolvectl status and direct dig @server. Fix VPN profile or DNS routing; avoid long search lists.
3) Symptom: getent hosts $(hostname) hangs, but dig works
Root cause: NSS order uses a slow source (mDNS, LDAP/SSSD) before DNS; dig bypasses NSS.
Fix: Adjust /etc/nsswitch.conf to prefer files, then dns. Confirm with timed getent.
4) Symptom: hostname -f is slow; sudo is slow; logs show FQDN lookups
Root cause: Hostname/FQDN mismatch plus search domain walking; reverse DNS absent, causing extra lookups.
Fix: Ensure consistent hostname strategy and a matching /etc/hosts entry; add PTR records if you run DNS.
5) Symptom: sudo slow only when domain controllers are unreachable
Root cause: SSSD/AD lookup delays influence NSS/PAM resolution paths.
Fix: Confirm with systemctl is-active sssd and timed getent. Fix SSSD failover/timeouts, and keep local hostname resolution in files.
6) Symptom: sudo delay appears after enabling Avahi or “desktop features” on a server
Root cause: mDNS gets tried and times out or is filtered, adding delay to lookups.
Fix: Remove/disable mDNS on servers or reorder NSS to avoid mDNS for non-.local lookups.
7) Symptom: sudo slow only on IPv6-enabled networks
Root cause: IPv6 DNS servers or routes are misconfigured; resolver tries AAAA then A with delays.
Fix: Check resolvectl status for v6 resolvers and test with dig -6. Fix routes or disable broken v6 resolvers; keep local hostname mapping.
8) Symptom: “sudo: unable to resolve host …” plus slowness
Root cause: Hostname does not resolve at all via NSS; sudo complains and waits on slow fallback.
Fix: Add correct entry to /etc/hosts for the hostname; verify with getent hosts $(hostname).
Checklists / step-by-step plan
Checklist A: One-host surgical fix (10 minutes, no meetings)
-
Measure the delay:
cr0x@server:~$ time sudo -n true sudo: a password is required real 0m2.101s user 0m0.008s sys 0m0.010sDecision: If real time is seconds with tiny CPU, proceed to name resolution checks.
-
Time NSS hostname lookup:
cr0x@server:~$ /usr/bin/time -f '%e seconds' getent hosts $(hostname) 2.00 seconds 10.22.1.17 server.corp.example serverDecision: If this is slow, fixing hostname resolution will likely fix sudo.
-
Add hostname mapping if missing:
cr0x@server:~$ sudo grep -nE '127\.0\.1\.1|127\.0\.0\.1' /etc/hosts 1:127.0.0.1 localhostcr0x@server:~$ sudoedit /etc/hostsDecision: Add
127.0.1.1 server.corp.example server(or your actual names). Save. -
Re-test:
cr0x@server:~$ /usr/bin/time -f '%e seconds' getent hosts $(hostname) 0.00 seconds 127.0.1.1 server.corp.example servercr0x@server:~$ time sudo -n true real 0m0.050s user 0m0.008s sys 0m0.012sDecision: If fixed, stop. You can now address DNS upstream without user-visible pain.
Checklist B: Fleet-level fix (the one you wish you’d done earlier)
- Standardize host identity: decide on short hostname vs FQDN policy.
- Enforce /etc/hosts baseline: local mapping for hostname and (if used) FQDN.
- Set NSS order intentionally:
hosts: files dnsfor servers unless you have a documented requirement. - Monitor lookup latency: alert on
getent hosts $(hostname)taking > 200ms sustained. - Fix PTR records for server subnets if you own DNS. Avoid “reverse DNS is optional” mythology.
- Test VPN/DHCP changes against a canary host by timing NSS lookups and
sudo.
Checklist C: If you must change DNS configuration
- Confirm who owns resolvers (network team, platform team, cloud provider).
- Verify reachability (UDP and TCP 53) from the affected subnet.
- Keep resolver lists short (2–3 servers) and local to the network region.
- Avoid long search domain lists; treat them as multipliers on failure.
- Roll out gradually and measure NSS latency, not just “dig works.”
FAQ
Why does sudo care about DNS at all?
Because it’s a policy/audit tool, not a raw privilege toggle. It may resolve hostnames for logging, policy context, or identity checks via NSS.
If NSS hits DNS and DNS is slow, sudo inherits that delay.
Why does dig look fast but sudo is slow?
dig talks to DNS directly. sudo uses libc name resolution via NSS, which can consult files, mDNS, SSSD/LDAP, and DNS—in that order.
You need to measure with getent, not just dig.
Is adding the hostname to /etc/hosts “bad practice”?
For local self-resolution, it’s good practice. You’re not replacing DNS for service discovery; you’re ensuring the machine can identify itself without the network.
This reduces the blast radius of DNS issues.
Should I use 127.0.1.1 or 127.0.0.1?
On Ubuntu, 127.0.1.1 is a common convention for mapping the host’s name without hijacking localhost.
Either can work, but keep localhost sane and avoid mapping multiple unrelated names to 127.0.0.1 casually.
What if the server’s “real” IP should be in DNS, not loopback?
Put the real IP in DNS (A/AAAA) and PTR in reverse DNS. Still keep a loopback mapping for the hostname if your environment tolerates it,
or map hostname to the primary IP in /etc/hosts if you must reflect reality. The goal is fast, consistent resolution.
Does systemd-resolved cause this?
systemd-resolved is often the messenger. It can surface bad upstream resolver lists, VPN-pushed DNS, or unreachable nameservers.
Use resolvectl status to see what it’s actually doing before blaming it.
Can IPv6 be the reason for the delay?
Yes. If your resolver setup includes broken IPv6 paths or unreachable IPv6 DNS servers, lookups can stall before falling back.
Measure with resolvectl and test v6 reachability; don’t disable IPv6 blindly unless you control the environment and accept the trade-offs.
Is it safe to edit /etc/nsswitch.conf to remove mDNS?
On servers, usually yes if you don’t rely on .local discovery. On desktops, removing mDNS can break device discovery.
Make the change intentionally and verify with timed getent hosts calls.
What’s the quickest “proof” that DNS is the bottleneck?
Time getent hosts $(hostname) and run strace on sudo looking for DNS socket timeouts.
If NSS resolution takes seconds, sudo isn’t your problem—name service is.
Why does it get worse on VPN?
VPNs often push internal DNS servers and long search domain lists. If the VPN path is lossy or the resolvers aren’t reachable from your current network,
each lookup becomes a timeout chain. Fix the VPN DNS profile or ensure local hostname resolution via /etc/hosts.
Next steps
If sudo is slow on Ubuntu 24.04, treat it like a dependency problem, not a sudo problem.
Measure with time, prove with strace, validate with getent.
Then make the fast path local: map your hostname in /etc/hosts and ensure files is first in host lookups.
After that, clean up the real cause: unreachable resolvers, overloaded DNS, silly search domains, missing PTR records, or enterprise name services timing out.
Do it calmly, with metrics, and with a canary host. Your future self will still be annoyed by DNS, but at least you won’t be waiting on it to type a password.