How to flush the DNS cache on Linux?

The Linux operating system is a popular choice among system developers. Users can browse websites by entering an URL (e.g., into the web browser. A URL also refers to a domain name.

To initiate a communication, it needs to be translated to the actual IP address of the server hosting the requested website.

The domain name server (DNS) translates an URL into an IP address by accessing a mapping database for the URLs to the IP addresses.

Domain Name System(DNS) is the protocol between the client and the lookup server. To perform the translation, the client sends a DNS request with the URL string and, in response, gets the IP address. 

The following example shows the IP address of a hosting server in response to a ping request for the domain name

# ping
PING ( 56(84) bytes of data.
64 bytes from ( icmp_seq=1 ttl=118 time=18.7 ms
64 bytes from ( icmp_seq=2 ttl=118 time=22.0 ms
64 bytes from ( icmp_seq=3 ttl=118 time=22.0 ms

Messages on wire with Wireshark analyzer. 

DNS Query Request/Response On Wire (Traces)

What is DNS caching On Linux?

In order to reduce the number of requests to browse a website, the operating system stores a temporary mapping between the domain name and corresponding IP address/addresses. Linux does not cache by default. Applications like Systemd-Resolved, DNSMasq, or NSCd must be installed to enable caching.

The examples in this tutorial will use Systemd-Resolved.

Upon activating a caching service, a DNS query is first sent to the DNS server for the first time. Thereafter, the cache generates the response locally for each subsequent request.

Why do we need DNS caching?

Caching means holding 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.

What is the purpose of flushing a cache, and when should it be done?

When the service pointed by the domain name is moved to another server with a different IP address than previously, if the cache is not flushed, the request will be routed to the previous IP address, at which point there will be no 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

If the service is not running, the status will be inactive.

Flush the cache:

#sudo systemd-resolve --flush-caches

Conclusion –

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