What the message looks like
sudo: unable to resolve host web01: Name or service not knownCommon causes
- The hostname was changed (
/etc/hostname,hostnamectl) but/etc/hostsstill holds the old name. - The current hostname is missing from
/etc/hostsand cannot be resolved through DNS either. - On cloud images cloud-init rewrites
/etc/hostsat every boot. - The
/etc/hostsfile is empty, damaged or contains typos. /etc/nsswitch.confwas altered so thatfilesis missing on thehosts:line.
Check
- Current hostname
hostname; cat /etc/hostname - Content of /etc/hosts
cat /etc/hosts - Does the name resolve?
getent hosts "$(hostname)" - Resolution order
grep '^hosts' /etc/nsswitch.conf
Fix
- Check the hostname and add a line to
/etc/hostsso it resolves, for example127.0.1.1 web01(customary on Debian and Ubuntu). - Edit the file with an editor:
sudo nano /etc/hosts. If sudo itself is a problem, usesu -. - If you renamed the machine, align hostname and file:
sudo hostnamectl set-hostname web01and put the same name in/etc/hosts. - On cloud instances mind the cloud-init setting
manage_etc_hosts; otherwise the entry is overwritten at the next boot. - Verify with
getent hosts "$(hostname)"andsudo truethat the warning is gone.
Typical scenario
A VPS was cloned from an ubuntu-base image and renamed with hostnamectl set-hostname web01. Since then every sudo prints the warning unable to resolve host web01 and waits a few seconds. /etc/hosts still holds the old name on the 127.0.1.1 line. After changing it to 127.0.1.1 web01 the warning is gone and sudo responds instantly.
FAQ
Is the message dangerous?
No, it is a warning with no security impact. sudo normally still runs the command, but it may wait for a DNS timeout and feel noticeably slow.
Which IP belongs in the hosts entry?
For a machine without a fixed address 127.0.1.1 (Debian convention) or 127.0.0.1 is enough. With a static IP you can use that instead, as long as the name resolves locally.
Why is sudo so slow with this?
If the name is not found locally, the resolver queries DNS servers and waits for their answer or timeout. A local entry in /etc/hosts avoids that wait.
How do I fix it if the error stops me writing to /etc/hosts?
The warning normally does not block sudo. If it does, log in as root (su - or the provider console) and edit the file there.
Do I need to reboot after the change?
No. /etc/hosts is read again on every lookup, so the change takes effect at once. Only on cloud instances must cloud-init be set so it does not overwrite the file at boot.