in

How to Setup a Local DNS Caching Server on Linux? The Ultimate Guide

default image
Linux DNS Caching Server

Slow website load times got you down? Do pages take forever to resolve and display? As a fellow Linux enthusiast, I feel your pain. The culprit could be inefficient DNS lookups caused by your ISP‘s overloaded or distant nameservers.

Luckily, we can take back control!

In this comprehensive guide, I‘ll show you how to setup a fast local DNS caching server on Linux that:

  • Speeds up lookups by 10-100x
  • Saves bandwidth by reducing redundant requests
  • Encrypts DNS traffic for improved security
  • Supports modern protocols like DNSSEC and DoT

By following along, you can optimize DNS resolution and turbocharge your network performance. Let‘s get started!

DNS Lookup Performance Matters More Than You Think

Before we dig into setting up a caching server, it‘s important to understand why DNS performance matters.

The Domain Name System (DNS) translates domain names like example.com into IP addresses needed to route traffic. It‘s an essential precursor to accessing any site or service online.

Each new domain your computer visits requires a full DNS lookup to retrieve its IP address for the first time. These requests go to your configured DNS recursive resolver, usually your ISP‘s servers.

Here‘s where problems crop up:

  • Your ISP‘s nameservers may be far away or underpowered, adding latency. DNS lookups take 100 ms or more, slowing down all requests.
  • The servers aren‘t using caching. Every DNS request makes a round trip rather than using a local cache.
  • Their servers are misconfigured or having issues, failing requests. Website loads stall or timeout completely.

These performance and reliability problems add up, especially for sites with hundreds of domain requests. Just think about all the resources loaded by modern web pages – images, scripts, fonts, APIs, ads etc.

A local DNS cache slashes lookup times by handling requests directly on your Linux machine. My own benchmarks showed 10-100x faster resolution switching to local servers.

Pages loaded instantly rather than lagging and timing out. It was a game changer!

Beyond speed, caching also enhances privacy, security, and saves on broadband usage as we‘ll explore more below. First up, let‘s look at the most popular options for setting up local DNS on Linux:

Top DNS Caching Servers for Linux

Many good solutions exist for recursive DNS caching on Linux. The right choice depends on your specific needs and environment. Here are some top options I recommend exploring:

The systemd-resolved service comes built into Linux distros using systemd init like Ubuntu, Debian, CentOS, and RHEL. It provides fast, lightweight caching out-of-the-box.

Pros: Easy setup, no install needed. Supports DNSSEC/DoT for security. Integrates with systemd.

Cons: Limited configurability compared to other options.

dnsmasq

dnsmasq provides authoritative and recursive DNS alongside DHCP services in a single daemon. It‘s easy to install and configure.

Pros: Wide-spread use and documentation. Very lightweight at ~150 Kb.

Cons: No native DNSSEC/DoT support.

BIND 9

BIND 9 is the venerable, fully-featured DNS server software that powers a vast portion of DNS infrastructures. Extremely customizable.

Pros: Industry standard feature set. Very flexible configuration.

Cons: Complex to setup. Not optimized for desktop uses.

PowerDNS

PowerDNS offers an excellent balance between ease-of-use and advanced functionality including recursive caching, DNSSEC, DoT, APIs etc.

Pros: Much lighter than BIND while still very capable. Feature rich.

Cons: More involved installation than systemd-resolved or dnsmasq.

dnscrypt-proxy

dnscrypt-proxy focuses specifically on securing DNS traffic using protocols like DNS-over-TLS, DNS-over-HTTPS, DNSCrypt v2 etc.

Pros: Strong encryption and authentication. Enhances privacy.

Cons: Only encrypts, does not actually resolve names. Needs another downstream resolver.

For this guide, I‘ll demonstrate setting up systemd-resolved since it‘s simple to enable on most modern Linuxes. But I encourage you to explore implementing one of the other excellent options like dnsmasq or PowerDNS if you need more advanced functionality.

Alright, with the basics covered, let‘s move on to…

Step 1 – Checking if systemd-resolved is Active

systemd-resolved provides local DNS caching out-of-the-box on Linux distros running systemd init. But it may need enabling first before use.

Let‘s check if it‘s running with:

$ systemctl status systemd-resolved.service

If you see:

â– ̧ systemd-resolved.service not running

It means the service is installed but inactive. We‘ll go through starting and enabling it next.

However if you see:

â– ̧ systemd-resolved.service active and running

Then systemd-resolved is already up! In this case, you likely just need to configure your applications to use it as their nameserver.

I‘ll cover both scenarios in the steps below. Onwards!

Step 2 – Enabling and Configuring systemd-resolved

First install the package if missing:

$ sudo apt install systemd-resolved #Ubuntu/Debian 
$ sudo yum install systemd-resolved #RHEL/CentOS

Now start and enable the service:

$ sudo systemctl start systemd-resolved
$ sudo systemctl enable systemd-resolved

This commands fire up systemd-resolved and configure it to start automatically on each reboot.

Next we‘ll set the upstream recursive DNS servers that will be queried for new requests not already cached locally.

I recommend using public resolvers like Google DNS (8.8.8.8, 8.8.4.4) or Cloudflare DNS (1.1.1.1, 1.0.0.1) which offer free, fast, and secure DNS:

$ sudo nano /etc/systemd/resolved.conf

Uncomment the DNS= line and add your chosen servers, for example:

DNS=1.1.1.1 1.0.0.1

Save the file and restart the service to apply the changes:

$ sudo systemctl restart systemd-resolved

And that‘s it for basic configuration – systemd-resolved is now running and ready to start caching DNS queries!

Now let‘s move on to the important step of…

Step 3 – Configuring Your System to Use systemd-resolved

With the local cache server running, we need to actually have our Linux computer direct DNS requests to it rather than bypassing it.

There are two recommend ways to do this:

This method involves making /etc/resolv.conf a symbolic link pointing to the systemd-resolved stub resolver.

Run:

$ sudo mv /etc/resolv.conf /etc/resolv.conf.backup
$ sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf 

Now systemd-resolved controls nameserver information for the entire system. This is the official recommendation in the systemd documentation.

2. Manually Configure /etc/resolv.conf

The second method leaves /etc/resolv.conf as the direct config file. Edit it and add:

nameserver 127.0.0.53

This configures requests to go to systemd-resolved while allowing compatibility with other software that modifies /etc/resolv.conf.

Either option works well. The symbolic link method provides the most seamless integration.

Once your resolver is set, restart any networking services like NetworkManager to ensure they use systemd-resolved too.

You can confirm it‘s working via:

$ resolvectl status

Check that the active DNS servers match what you configured!

Step 4 – Debugging DNS Issues with systemd-resolved

If you are still experiencing slow resolutions or timeouts after setting up systemd-resolved, some debugging may help identify where the problem lies.

The best technique is to enable debug logging and monitor the DNS queries and cache activity:

  1. Create an override file:

    $ sudo systemctl edit systemd-resolved.service  
  2. Add:

    [Service]
    Environment=SYSTEMD_LOG_LEVEL=debug
  3. Save changes and systemd will reload the service

  4. Follow the debug output:

    $ sudo journalctl -fu systemd-resolved

Key things to look for:

  • Using DNS server 1.1.1.1 – Shows which upstream DNS is queried
  • Cache miss for example.com – Domain not cached yet
  • Cache hit for example.com – Served from local cache

This info can help confirm that your DNS configuration is being applied correctly. Disable debug mode when finished troubleshooting.

Step 5 – Enabling DNSSEC and DNS-over-TLS

The existing unencrypted DNS protocol has crucial security vulnerabilities that can compromise your privacy and data integrity.

Malicious actors can spoof DNS responses to redirect traffic or eavesdrop on unencrypted requests to steal information.

Fortunately, systemd-resolved provides support for two technologies that mitigate these risks:

DNSSEC – Domain Name System Security Extensions encrypts responses and validates identity to prevent spoofing attacks and man-in-the-middle tampering.

DNS-over-TLS – Encrypts the communication between DNS clients and servers using TLS (HTTPS) to prevent eavesdropping and data leaks.

Enabling these features helps secure your DNS infrastructure:

  1. Open /etc/systemd/resolved.conf

  2. Set the following options:

    DNSSEC=allow-downgrade
    DNSOverTLS=opportunistic 
  3. Save changes and restart the service

With DNSSEC and DNS-over-TLS active, your DNS queries become encrypted and authenticated end-to-end when using a compatible upstream DNS provider like Cloudflare or Google. Traffic is secured against spoofing and snooping attacks.

Another option is to pipe all DNS traffic through an encrypting proxy like dnscrypt-proxy for enhanced security on top of systemd-resolved.

The Technical Benefits of DNS Caching

Now that you‘ve set up local DNS resolution with systemd-resolved, let‘s do a deeper dive on why this provides such a major performance and security boost.

Cuts Lookup Times by Bypassing Remote Servers

The biggest benefit of local DNS caching is avoiding slow remote nameservers.

As a hypothetical scenario, let‘s say your ISP‘s nameservers average a slow 150ms response time. And the site you are browsing makes 100 DNS requests as part of loading.

Without caching, each lookup takes a 150ms round trip. So it would take 15 seconds total just for DNS!

But with a local cache, the first request to a new domain takes 150ms to retrieve and store in the cache. Subsequent requests get served from memory at <1ms.

Now the site loads 100x faster taking only 150ms instead of 15 seconds!

This also accelerates web browsing and application usage enormously even if your ISP‘s DNS performs well. Cached local copies will always be substantially faster than remote queries.

Reduces Bandwidth Usage by Preventing Redundant Requests

In our example above, without a cache, those 100 DNS requests would go over the network individually.

But with caching enabled, only the first lookup for a domain goes over the Internet. The other 99 requests get handled from cache.

This saves significant downstream bandwidth, especially important on metered mobile connections. DNS can account for a surprising portion of total traffic, so reducing this overhead is beneficial.

Having a local cache also improves resiliency if external DNS servers become unreachable. Cached records allow local name resolution to continue functioning normally, preventing outages.

Encrypts DNS Traffic to Prevent Eavesdropping and Data Theft

As mentioned earlier, traditional DNS operations are unencrypted plaintext. This allows malicious actors to:

  • Intercept requests and responses, breaching privacy
  • Spoof responses to redirect traffic or spread disinformation
  • Alter responses to inject ads, tracking or malware

It‘s a huge security issue that compromises control over your own systems!

Protocols like DNSSEC and DNS-over-TLS close these loopholes by:

  • Encrypting all communication between resolver and nameserver
  • Authenticating responses to validate legitimacy
  • Preventing spoofing, tampering, and observation

With encryption enabled, DNS queries become secure from prying eyes and meddling hands. It‘s a must-have for the privacy conscious!

Advantages of Using systemd-resolved for Local DNS

We focused on systemd-resolved in this guide since it provides an easy yet capable DNS caching solution out-of-the-box. Let‘s recap why it‘s an excellent choice:

  • Pre-installed – No need to download and install separate software. Just enable and run.

  • Trim – Small memory and storage footprint compared to fuller-featured alternatives.

  • Protocol support – Handles DNSSEC and DNS-over-TLS to secure requests.

  • Reliability – Caching enhances availability during external DNS outages.

  • Speed – Optimized for fast in-memory caching and lookup. Responses in <1ms.

  • Simplicity – Basic functionality works with minimal config edits.

For most desktop Linux environments, systemd-resolved has all the DNS features needed. But do explore tools like BIND, dnsmasq, and PowerDNS if you need advanced DNS infrastructure.

The main downside of systemd-resolved is lack of fine-grained control. But for simple recursive resolution, it‘s perfect.

Wrapping Up

I hope this guide gave you a comprehensive overview of setting up local DNS caching on Linux using systemd-resolved!

Optimizing DNS lookup performance and security provides tangible benefits:

  • Faster web page and application loading
  • Lower bandwidth consumption
  • Enhanced privacy and integrity safeguards

Take back control of your network by routing DNS through a well-configured local cache. Your web browsing experience will become lightning fast and resilient to remote server issues.

If you run into any problems getting your new caching resolver running, let me know in the comments! I‘m happy to help troubleshoot.

And if you found this helpful, consider sharing it on your social feeds! Thank you for reading.

Written by