Configure Local DNS Caching on Linux

PowerADM.com / Linux / Debian / Configure Local DNS Caching on Linux

On most modern Linux distros, you can enable the local caching of DNS queries by using the built-in systemd-resolved service. In this article, we will take a look at how to speed up the resolution of DNS queries by using systemd-resolved local client caching on Debian and Ubuntu. This allows you to reduce DNS resolution delays if you have an unstable network connection, when DNSSEC is enabled, and on hosts that make a large number of DNS queries (for example, mail servers).

Unlike dnsmasq or unbound, systemd-resolved is pre-installed on Ubuntu 18.04 and newer and doesn’t need to be installed separately.

Check that systemd-resolved is running:

$ systemctl status systemd-resolved

Check the current system-resolved settings:

$ systemd-resolve --status

In Ubuntu 22.04+ the utility has been renamed to resolvectl, so you need to run a different command:

$ resolvectl status

DNS caching client with systemd-resolved

You need to install libnss-resolve package, a plugin for the NSS (GNU Name Service Switch), for apps to perform name resolution via systemd-resolve.

$ sudo apt-get install libnss-resolve

In this case, the hosts: files dns line in /etc/nsswitch.conf will be replaced to:

hosts: files mdns4_minimal [NOTFOUND=return] resolve [!UNAVAIL=return] dns

Edit the file /etc/systemd/resolved.conf (all settings are commented out by default):

[Resolve]
DNS=8.8.8.8 8.8.4.4
FallbackDNS= 1.1.1.1 1.0.0.1
DNSSEC=no
DNSOverTLS=no
Cache=yes

To ensure compatibility with applications that do not use library calls, but instead access the DNS server directly, you will need to create a symbolic link to it:

# ln -svi /run/systemd/resolve/resolv.conf /etc/resolv.conf

Start systemd-resolved:

# systemctl enable systemd-resolved
# systemctl restart systemd-resolved

Now the main DNS configuration file on the computer is /etc/systemd/resolved.conf.

Enable debug mode to see how the DNS lookup cache is being used:

# systemctl edit systemd-resolved

Add:

[Service]
Environment=SYSTEMD_LOG_LEVEL=debug

Open the service log:

# journalctl -f -u systemd-resolved

The log will now contain the following lines when you resolve the same DNS name again:

Looking up RR for poweradm.com IN A.
Cache miss for poweradm.com IN A
….
Looking up RR for poweradm.com IN AAAA.
Positive cache hit for poweradm.com IN A

You can get DNS query caching statistics like this:

$ systemd-resolve --statistics

Clear local DNS cache:

$ systemd-resolve --flush-caches
Leave a Reply

Your email address will not be published. Required fields are marked *