Linux for Wireless Engineers: How to Do DNS Caching with dnsmasq

By October 30, 2019Linux

Dnsmasq is Linux utility which provides DNS, DHCP, TFTP and DNS caching capabilities. It’s a very lightweight service, is available for most Linux distribution, and has found wide adoption for Android as well as OS X users. In this post, we’ll talk about the DNS caching part.


This could be my shortest post yet! Because if you want add DNS caching on your Linux box, it is as simple as this:

That’s it! 

If you want to test what difference this makes, I recommend using dig because it depicts the time it takes to do a DNS lookup. So, let’s try to resolve “” with dig (I am using the “+noall +stats” options to make the output more readable):

As you can see, this lookup took 23 mseconds. Now, if I rerun the same command the lookup will take 0 mseconds!

That’s because dnsmasq cached the information after the first lookup, and all subsequent lookups don’t take any time because they are served from the cache.

If you want to clear the cache you have to restart the dnsmasq as follows:


There are few options you can change in the dnsmasq configuration file “/etc/dnsmasq.conf”. Below, I am copying the three options from the configuration file skeleton:

The default value for the cache size is 150 and if you set it to 0, you can disable caching. A large cache size might impact performance because dnsmasq keeps all caching in memory. 

If you lookup a domain that is invalid (e.g., by default dnsmasq caches this information and returns “no such domain” from its cache every time you lookup the same invalid domain. If you want to disable this functionality, you can comment in the option ‘no-negcache’ 

The ‘local-ttl’ option is fully explained in the dnsmasq.conf.

Keep in mind that each time you change an option, you have to restart dnsmasq with ‘systemctl restart dnsmasq’ to reload the new option. As mentioned above, restarting it clears the cache as well.

How it works

On Debian-based Linux all DNS servers are listed in the file ‘/etc/resolv.conf’ For example, whenever a host gets a DNS servers from DHCP, it adds it in this file.

Dnsmasq needs to redirect all DNS queries to itself. To do that, upon launching, it replaces the nameservers in ‘/etc/resolv.conf’ with Here is how ‘/etc/resolv.conf’ looks like before dnsmasq starts:

And here is how it looks like after dnsmasq starts:

By default, dnsmasq saves the original resolv.conf file in  ‘/run/dnsmasq/resolv.conf’. If you stop it with ‘sudo systemctl stop dnsmasq’, it restores the original resolv.conf file.

If you are only looking for DNS caching on your Linux host, dnsmasq requires zero set up and configuration after installation. In addition, it’s lightweight, well supported, and documented. In future blog posts we’ll talk about the dnsmasq DHCP, DNS, and TFTP servers – stay tuned!