How to flush DNS cache on Linux?


Linux is one of the popular operating systems among developers. A Linux user can browse a website by entering an URL (e.g www.google.com) in the web browser.  An URL is a string known as a domain name.

To start a communication, it needs to translate to the actual IP address of the server that hosts the requested website.

A domain name server is the network entity that translates an URL into an IP address by using a mapping database for URL to IP address.

Linux uses Domain Name System protocol between the client and the DNS server.  To perform the translation, the client sends a DNS request with the URL name and in response gets the IP address back.  For example, if you ping a URL you can see the IP address of the server in response.

# ping www.google.com
PING www.google.com (142.250.192.196) 56(84) bytes of data.
64 bytes from del11s12-in-f4.1e100.net (142.250.192.196): icmp_seq=1 ttl=118 time=18.7 ms
64 bytes from del11s12-in-f4.1e100.net (142.250.192.196): icmp_seq=2 ttl=118 time=22.0 ms
64 bytes from del11s12-in-f4.1e100.net (142.250.192.196): icmp_seq=3 ttl=118 time=22.0 ms

Messages on wire with Wireshark analyzer. 

DNSRequestOnWire
DNSRequestOnWire

What is DNS caching On Linux?

To reduce the number of requests to browse a website, the operating system stores the temporary mapping between the domain name and corresponding IP address/addresses. By default, Linux does not cache.  There are applications such as Systemd-Resolved, DNSMasq, or Nscd any one of them should be installed and running.

After activating a caching service, a DNS query is sent to the DNS server for the first time and after that, for consecutive requests, the response is generated locally by the cache.

Why do we need DNS caching?

Caching means to hold something for a shorter time.  It is an optional mechanism, that provides an optimization of the network bandwidth.  Responding locally reduces the network delay and enriches the user experience.

When/Why do we need to flush a cache?

If the service that is pointed by the domain name has been sifted to another server with a different IP address than earlier.  If we will not flush the cache, the request will go to the older IP address and we will not get any response.

How to check and clear the cache with systemd-resolved?

Check if caching is active:

If you are running the system-resolved demon for DNS caching you can check the status with the following command and flush with the –flush-caches option.

#systemctl is-active systemd-resolved.service
active

If the service is not running status will be inactive.

Flush the cache:

#sudo systemd-resolve --flush-caches

Conclusion –

You have learned what is domain name resolution caching and how we can clear the cache.  In another tutorial, we will cover the same on Windows operating system.