patternbashTip
/etc/hosts Override: Local DNS for Development and Blocking
Viewed 0 times
/etc/hostsdns overridensswitchlocal dnshostname resolutionhosts file
linux
Problem
Need to override DNS resolution for specific hostnames locally without modifying a DNS server — for development, testing, or blocking domains.
Solution
Edit
/etc/hosts to map hostnames to IP addresses. Entries take precedence over DNS (by default).# View current entries
cat /etc/hosts
# Add a local dev domain (requires root)
sudo tee -a /etc/hosts <<EOF
127.0.0.1 myapp.local
127.0.0.1 api.myapp.local
192.168.1.50 staging.internal
EOF
# Flush DNS cache after editing (systemd-resolved)
sudo systemd-resolve --flush-caches
# Verify resolution
getent hosts myapp.localWhy
The OS resolves
/etc/hosts before querying DNS (controlled by nsswitch.conf). This makes it useful for development environments, blocking ad domains, and overriding production hostnames for testing.Gotchas
- The precedence order is defined in
/etc/nsswitch.confunder thehosts:line — not alwaysfilesfirst. - Some browsers and applications (especially those with DNS-over-HTTPS) bypass
/etc/hostsentirely. - Changes take effect immediately for new connections but cached lookups in long-running processes won't update.
- Trailing whitespace or invisible characters in entries cause silent resolution failures.
Revisions (0)
No revisions yet.