How to Clear DNS Cache on Amazon Linux AMI When Standard Methods Fail


4 views

Amazon Linux AMI, being a customized distribution for AWS environments, handles DNS differently than standard Linux distributions. Many engineers encounter frustration when traditional DNS flushing commands like service nscd restart or systemd-resolve --flush-caches don't work.

Unlike Ubuntu or CentOS, Amazon Linux AMI doesn't include these common DNS caching services by default:

# These won't work on vanilla Amazon Linux AMI:
sudo service nscd restart
sudo systemctl restart dnsmasq
sudo /etc/init.d/dns-clean restart

Here are proven methods to clear DNS resolution in Amazon Linux:

Method 1: Restart Network Interface

sudo /etc/init.d/network restart
# Alternative for newer Amazon Linux 2:
sudo systemctl restart network

This forces the system to re-resolve all hostnames while maintaining existing connections.

Method 2: Use dhclient

sudo dhclient -r eth0  # Release current DHCP lease
sudo dhclient eth0     # Renew lease and DNS info

Method 3: Clear Specific Application Caches

For applications maintaining their own DNS cache:

# For Java applications:
echo "InetAddress.getLocalHost().getHostName()" | jshell

# For Python scripts:
import socket
socket.gethostbyname('example.com')

To prevent DNS caching issues in your Amazon Linux instances:

# Edit /etc/sysconfig/network and add:
NOZEROCONF=yes
NETWORKING=yes

# Then run:
sudo chkconfig network on

After clearing cache, always verify with:

dig example.com
nslookup example.com
getent hosts example.com

Amazon Linux AMI, being a minimal distribution optimized for AWS, doesn't include common DNS caching services like nscd or dnsmasq by default. This often confuses administrators coming from other Linux distributions where these services are standard.

First, verify what DNS resolution mechanisms are active:

# Check running processes
ps aux | grep -E 'nscd|dnsmasq|systemd-resolved'

# Examine name resolution configuration
cat /etc/resolv.conf
cat /etc/nsswitch.conf

When traditional methods don't work, try these alternatives:

1. Restarting Network Services

sudo /etc/init.d/network restart
# Or for newer AMIs
sudo systemctl restart network

2. Using dhclient

sudo dhclient -r eth0  # Release
sudo dhclient eth0     # Renew

3. Manual Flush via resolvconf

sudo resolvconf -u

For environments requiring regular DNS cache management:

# Install dnsmasq if needed
sudo yum install dnsmasq -y
sudo service dnsmasq restart

# Or install nscd
sudo yum install nscd -y
sudo service nscd restart

After any flush operation, verify with:

dig example.com
nslookup example.com
getent hosts example.com

Remember that Amazon Linux uses DHCP-backed networking. The VPC's DNS server (usually 169.254.169.253) may maintain its own cache independent of your instance.