How to resolve DNS and use /etc/hosts
Topic: Servers linux
Summary
Configure and test DNS resolution: set nameservers in resolv.conf or netplan, use getent and dig to verify; add static entries in /etc/hosts when you need a fixed name without DNS. Use this when the server cannot resolve hostnames or you need to override a name.
Intent: How-to
Quick answer
- Nameservers: /etc/resolv.conf (nameserver 8.8.8.8) or in netplan/NetworkManager; getent hosts example.com or dig example.com to test.
- /etc/hosts: add line 'IP FQDN shortname'; checked before DNS by default (nsswitch.conf order); use for local overrides or when DNS is down.
- If resolv.conf is overwritten: set nameservers in netplan (resolve section) or in NM; avoid editing resolv.conf directly on systems that manage it.
Prerequisites
Steps
-
Check current DNS config
cat /etc/resolv.conf; cat /etc/nsswitch.conf (hosts: files dns); getent hosts example.com; dig example.com +short.
-
Set nameservers
Netplan: nameservers.addresses in the interface; NM: nmcli con mod ID ipv4.dns '8.8.8.8 1.1.1.1'; then netplan apply or NM reload; verify resolv.conf.
-
Add /etc/hosts entry
echo '192.168.1.10 myapp.local myapp' | sudo tee -a /etc/hosts; getent hosts myapp.local; use for local dev or overrides.
-
Verify and debug
getent hosts name; dig name; nslookup name; if fail check resolv.conf and firewall (outbound 53); check /etc/hosts for wrong entry.
Summary
You will configure DNS (resolv.conf or netplan/NM), test resolution with getent and dig, and add static entries in /etc/hosts when needed. Use this when the server cannot resolve names or you need a local override.
Prerequisites
- Root or sudo; network connectivity.
Steps
Step 1: Check current DNS config
cat /etc/resolv.conf
getent hosts google.com
dig google.com +short
Step 2: Set nameservers
In netplan add under the interface: nameservers: addresses: [8.8.8.8, 1.1.1.1]. Then netplan apply.
Step 3: Add /etc/hosts entry
echo '192.168.1.10 myapp.local' | sudo tee -a /etc/hosts
getent hosts myapp.local
Step 4: Verify and debug
- getent and dig succeed; wrong or stale entry in hosts can break resolution—edit or remove it.
Verification
- Resolution works for a test name; /etc/hosts used when expected (order in nsswitch.conf).
Troubleshooting
resolv.conf overwritten — Managed by systemd-resolved or NM; set DNS in netplan or NM, not directly in resolv.conf.
Slow resolution — Check DNS server reachability; reduce timeout or use a closer DNS; check for IPv6 attempts that hang.