Configuring DNS Servers in Linux

Linux DNS server v4 configuration workflow showing editing /etc/resolv.conf, named.conf, zone files, systemd-resolved settings, testing with dig, nslookup, and restarting services.

Configuring DNS Servers in Linux
SPONSORED

Sponsor message — This article is made possible by Dargslan.com, a publisher of practical, no-fluff IT & developer workbooks.

Why Dargslan.com?

If you prefer doing over endless theory, Dargslan’s titles are built for you. Every workbook focuses on skills you can apply the same day—server hardening, Linux one-liners, PowerShell for admins, Python automation, cloud basics, and more.


Configuring DNS Servers in Linux

Every time you access a website, send an email, or connect to any online service, your system relies on Domain Name System (DNS) servers working silently in the background. These critical components translate human-readable domain names into machine-readable IP addresses, making the internet navigable and accessible. Without properly configured DNS servers, your Linux system would struggle to communicate with the outside world, leaving you isolated in a digital void. Understanding how to configure and manage DNS settings isn't just a technical skill—it's fundamental knowledge for anyone working with Linux systems, whether you're managing a home server or enterprise infrastructure.

DNS configuration in Linux encompasses the processes, files, and tools that determine how your system resolves domain names to IP addresses. This involves understanding resolver configuration files, managing nameserver priorities, implementing DNS caching solutions, and troubleshooting resolution failures. The landscape includes multiple approaches—from traditional configuration files to modern systemd-resolved implementations—each with distinct advantages and use cases that serve different networking scenarios.

Throughout this comprehensive guide, you'll discover the essential configuration files that control DNS behavior, learn practical commands for testing and troubleshooting resolution issues, explore various DNS management tools available in different distributions, and understand how to implement both temporary and persistent DNS configurations. You'll gain insights into security considerations, performance optimization techniques, and best practices that ensure reliable name resolution across diverse network environments. Whether you're troubleshooting connectivity issues or architecting complex network infrastructures, this knowledge will empower you to take complete control of DNS functionality on your Linux systems.

Understanding DNS Resolution in Linux Systems

The DNS resolution process in Linux involves multiple layers of configuration and several key components working together. At its core, the system needs to know which DNS servers to query, in what order, and how to handle various resolution scenarios. The traditional approach centers around the /etc/resolv.conf file, which has been the standard configuration point for decades. However, modern Linux distributions have introduced additional complexity with tools like NetworkManager, systemd-resolved, and resolvconf, each offering different management paradigms.

When an application needs to resolve a domain name, it doesn't directly query DNS servers. Instead, it calls resolver functions from the system's C library (glibc), which then consults configuration files to determine the resolution strategy. This process involves checking local hosts files, querying configured nameservers, and applying search domains and options that modify resolution behavior. The Name Service Switch (NSS) configuration in /etc/nsswitch.conf determines which sources are consulted and in what order, allowing for flexible resolution strategies that can include local files, DNS, mDNS, and other naming services.

"The resolver configuration is the foundation of network connectivity—get it wrong, and nothing else matters. Every network transaction depends on accurate name resolution."

Different Linux distributions handle DNS configuration differently, reflecting their design philosophies and target use cases. Traditional server distributions often maintain direct control through static resolv.conf files, while desktop-oriented distributions typically employ NetworkManager to dynamically manage DNS settings based on network connections. Understanding these differences is crucial because configuration methods that work on one distribution may not apply to another, and attempting to manually edit files managed by automated systems can lead to configurations being overwritten without warning.

The Role of /etc/resolv.conf

The resolv.conf file serves as the primary configuration point for DNS resolution in most Linux systems. This simple text file contains directives that specify nameserver addresses, search domains, and various options that control resolver behavior. Despite its simplicity, this file wields enormous influence over network functionality. Each nameserver directive specifies a DNS server IP address, with the resolver querying them in the order listed until receiving a response or exhausting all options.

Search domains, specified with the search directive, automatically append domain suffixes to unqualified hostnames, simplifying name resolution within organizational networks. For example, if your search domain is "example.com" and you query "server1," the resolver automatically tries "server1.example.com" before failing. The domain directive serves a similar purpose but only specifies a single local domain. Options like timeout, attempts, and rotate fine-tune resolver behavior, controlling how long to wait for responses, how many times to retry failed queries, and whether to distribute queries across multiple nameservers.

Directive Purpose Example Limitations
nameserver Specifies DNS server IP address nameserver 8.8.8.8 Maximum of 3 nameservers
search Defines search domain list search example.com corp.local Maximum 6 domains, 256 characters total
domain Sets local domain name domain example.com Only one domain allowed
options timeout Sets query timeout in seconds options timeout:2 Default is 5 seconds
options attempts Number of query retries options attempts:3 Default is 2 attempts
options rotate Rotates through nameservers options rotate Round-robin distribution

Modern DNS Management Systems

Contemporary Linux distributions increasingly rely on sophisticated DNS management systems that dynamically update resolv.conf based on network state. NetworkManager has become the standard for desktop and laptop systems, automatically configuring DNS settings when connecting to networks via DHCP or manual configuration. It maintains its own internal DNS configuration and generates resolv.conf dynamically, often creating it as a symbolic link to a file it manages. This approach works well for mobile systems that frequently change networks but can complicate manual DNS configuration.

The systemd-resolved service represents a more modern approach, providing not just DNS resolution but also DNSSEC validation, DNS-over-TLS support, and local DNS caching. When active, it typically runs a local DNS stub resolver on 127.0.0.53, with resolv.conf pointing to this local service. This architecture provides significant benefits including improved performance through caching, enhanced security through DNSSEC, and better integration with systemd's network management. However, it also introduces complexity and potential conflicts with other DNS management tools.

"Modern DNS management isn't just about pointing to a nameserver—it's about security, privacy, performance, and seamless integration with dynamic network environments."

Understanding which system manages DNS on your distribution is essential before attempting configuration changes. Running systemctl status systemd-resolved reveals whether systemd-resolved is active, while checking if resolv.conf is a symbolic link indicates automated management. On systems where NetworkManager controls DNS, using nmcli commands provides the proper interface for configuration changes that will persist across network changes and system reboots.

Manual DNS Configuration Methods

Direct manipulation of DNS configuration files remains the most straightforward approach on servers and systems not using automated network management. This method provides complete control and transparency, making it ideal for static server environments where network configuration rarely changes. The process involves editing /etc/resolv.conf with a text editor and adding the appropriate directives. However, this simplicity comes with the responsibility of ensuring configurations persist across reboots and aren't overwritten by other services.

Before making any changes, always create a backup of the existing configuration. This simple precaution allows quick recovery if new settings cause resolution failures. Use a command like sudo cp /etc/resolv.conf /etc/resolv.conf.backup to preserve the current state. When editing the file, maintain a logical order: nameserver directives should appear first, followed by search or domain directives, and finally any options. This organization isn't strictly required but makes the configuration more readable and maintainable.

# Example /etc/resolv.conf configuration
# Primary DNS server (Google Public DNS)
nameserver 8.8.8.8
# Secondary DNS server (Cloudflare DNS)
nameserver 1.1.1.1
# Tertiary DNS server (Quad9)
nameserver 9.9.9.9
# Search domains for hostname completion
search example.com internal.example.com
# Resolver options
options timeout:2 attempts:3 rotate

Preventing Configuration Overwrites

One of the most frustrating aspects of manual DNS configuration is having your carefully crafted settings overwritten by DHCP clients, NetworkManager, or other automated tools. Several strategies prevent this problem, each with different trade-offs. The most direct approach involves making resolv.conf immutable using the chattr +i /etc/resolv.conf command. This filesystem-level protection prevents any process, even running as root, from modifying the file until the immutable attribute is removed with chattr -i.

A more sophisticated approach involves configuring DHCP clients to ignore DNS information from DHCP servers. In systems using dhclient, editing /etc/dhcp/dhclient.conf and adding supersede domain-name-servers with your preferred DNS servers ensures your choices take precedence. For systems using dhcpcd, similar configuration in /etc/dhcpcd.conf with the nohook resolv.conf directive prevents the DHCP client from updating DNS settings entirely.

  • 🔒 Immutable attribute: Prevents all modifications until explicitly removed, providing the strongest protection but requiring manual intervention for legitimate changes
  • ⚙️ DHCP client configuration: Allows you to specify which DNS servers to use while still accepting other DHCP settings like IP address and gateway
  • 🔗 Symbolic link method: Points resolv.conf to a file in a location that automated tools don't manage, though some tools may remove and recreate the link
  • 📝 NetworkManager configuration: Uses NetworkManager's own configuration files to specify DNS servers, working with rather than against the management system
  • 🛡️ Systemd-resolved configuration: Configures DNS through resolved.conf, leveraging the service's capabilities while maintaining automated management benefits

Distribution-Specific Configuration Approaches

Different Linux distributions employ varying mechanisms for DNS configuration, reflecting their design philosophies and target audiences. Ubuntu and Debian systems traditionally used resolvconf as an intermediary system, with various network configuration tools updating DNS settings through this framework. Modern versions increasingly rely on systemd-resolved, requiring configuration through /etc/systemd/resolved.conf rather than direct resolv.conf editing. The resolved.conf file supports similar directives but with slightly different syntax and additional options for DNSSEC and DNS-over-TLS.

Red Hat Enterprise Linux, CentOS, and Fedora systems use NetworkManager by default, even on servers in recent versions. DNS configuration belongs in network interface configuration files located in /etc/sysconfig/network-scripts/ for older versions or managed through NetworkManager connection profiles. Adding DNS1, DNS2, and DNS3 directives to interface configuration files ensures settings persist across reboots and network restarts. Alternatively, using nmcli con mod commands provides a more modern interface for the same configuration.

"Understanding your distribution's network management philosophy isn't optional—it's the difference between configurations that persist and those that vanish after the next reboot."

Arch Linux and its derivatives offer maximum flexibility, supporting multiple DNS management approaches without forcing a particular method. Users can choose between manual resolv.conf management, systemd-resolved, NetworkManager, or other tools based on their needs. This flexibility is powerful but requires understanding the implications of each choice. Alpine Linux, often used in containers, typically uses simple static configuration through /etc/resolv.conf, making it straightforward to configure but requiring manual updates when network conditions change.

Working with NetworkManager

NetworkManager provides a comprehensive network management framework that handles DNS configuration as part of its broader connection management responsibilities. Rather than directly editing configuration files, you interact with NetworkManager through command-line tools, graphical interfaces, or configuration files it manages. This approach ensures consistency between DNS settings and other network parameters, automatically updating DNS when switching between networks, and providing fallback mechanisms when primary DNS servers become unavailable.

The nmcli command-line tool offers complete control over NetworkManager configuration. To view current DNS settings, use nmcli dev show which displays detailed information about all network devices including their configured DNS servers. To modify DNS settings for a specific connection, use the nmcli con mod command with the connection name and new DNS servers. For example, nmcli con mod "Wired connection 1" ipv4.dns "8.8.8.8 1.1.1.1" sets Google and Cloudflare DNS servers for the specified connection.

# View all NetworkManager connections
nmcli con show

# Display detailed information for a specific connection
nmcli con show "Wired connection 1"

# Set DNS servers for a connection
nmcli con mod "Wired connection 1" ipv4.dns "8.8.8.8 1.1.1.1"

# Add an additional DNS server without replacing existing ones
nmcli con mod "Wired connection 1" +ipv4.dns "9.9.9.9"

# Ignore DNS servers provided by DHCP
nmcli con mod "Wired connection 1" ipv4.ignore-auto-dns yes

# Apply changes by reconnecting
nmcli con down "Wired connection 1" && nmcli con up "Wired connection 1"

NetworkManager Configuration Files

Behind the nmcli interface, NetworkManager stores connection configurations in files located in /etc/NetworkManager/system-connections/. These INI-style configuration files contain all parameters for each network connection, including DNS settings. While nmcli provides the preferred interface for modifications, understanding the file format enables advanced configurations and troubleshooting. Each connection file includes sections like [connection], [ipv4], and [ipv6], with DNS servers specified in the relevant IP version section.

Direct editing of these files requires appropriate permissions and understanding of the format. After making changes, you must reload NetworkManager configuration with nmcli con reload or restart the NetworkManager service. The [ipv4] section includes dns entries that list DNS servers separated by semicolons, and ignore-auto-dns boolean values that determine whether to accept DNS servers from DHCP. Similar parameters exist in the [ipv6] section for IPv6 DNS configuration.

"NetworkManager's abstraction layer isn't about hiding complexity—it's about managing complexity intelligently, adapting to changing network conditions while maintaining user preferences."

Global DNS Configuration in NetworkManager

Beyond per-connection DNS settings, NetworkManager supports global DNS configuration that applies across all connections. This proves particularly useful for implementing organization-wide DNS policies or ensuring certain DNS servers are always available regardless of network connection. The /etc/NetworkManager/NetworkManager.conf file and drop-in files in /etc/NetworkManager/conf.d/ allow global DNS configuration through the [global-dns] section.

Global DNS configuration can specify default servers, configure DNS priority, and implement split DNS scenarios where different domains resolve through different DNS servers. This advanced functionality supports complex enterprise networks where internal resources use internal DNS servers while external queries use public DNS. The configuration uses domain-specific DNS server specifications, allowing precise control over resolution paths for different namespaces.

Configuration Method Scope Persistence Best Use Case
nmcli con mod Per-connection Permanent Setting DNS for specific network connections
Connection config files Per-connection Permanent Advanced per-connection customization
NetworkManager.conf Global Permanent System-wide DNS policies
conf.d drop-ins Global Permanent Modular global configurations
GUI tools (nm-applet) Per-connection Permanent Desktop user-friendly configuration

Systemd-Resolved Configuration and Management

The systemd-resolved service represents a paradigm shift in Linux DNS management, providing not just basic name resolution but a comprehensive DNS client with caching, DNSSEC validation, and modern protocol support. When active, it runs a local DNS stub resolver on 127.0.0.53, with applications sending DNS queries to this local service rather than directly to external DNS servers. This architecture enables sophisticated features like per-interface DNS configuration, automatic fallback between DNS servers, and transparent DNSSEC validation without application awareness.

Configuration occurs primarily through /etc/systemd/resolved.conf, where you specify DNS servers, fallback DNS servers, domains, and various options controlling resolution behavior. The configuration file uses an INI-style format with a [Resolve] section containing directives like DNS, FallbackDNS, Domains, DNSSEC, DNSOverTLS, and Cache. Changes to this file require restarting the systemd-resolved service with systemctl restart systemd-resolved to take effect.

# Example /etc/systemd/resolved.conf configuration
[Resolve]
# Primary DNS servers
DNS=8.8.8.8 1.1.1.1 2001:4860:4860::8888
# Fallback DNS servers used when primary servers are unreachable
FallbackDNS=9.9.9.9 149.112.112.112
# Search domains
Domains=example.com
# Enable DNSSEC validation
DNSSEC=yes
# Enable DNS over TLS
DNSOverTLS=opportunistic
# Enable local DNS caching
Cache=yes
# Enable multicast DNS
MulticastDNS=yes

Understanding Systemd-Resolved Architecture

Systemd-resolved implements several sophisticated features that distinguish it from traditional DNS resolution. The local caching functionality stores successful DNS responses, dramatically reducing resolution latency for frequently accessed domains and decreasing load on upstream DNS servers. The cache operates transparently, with applications unaware that cached data is being served rather than fresh queries. Cache entries respect TTL values from DNS responses, automatically refreshing when data expires.

DNSSEC validation provides cryptographic verification of DNS responses, protecting against DNS spoofing and cache poisoning attacks. When enabled, systemd-resolved validates DNSSEC signatures on responses from DNSSEC-enabled domains, rejecting responses that fail validation. This security feature operates transparently to applications, though it can cause resolution failures for misconfigured DNSSEC domains. The DNSSEC setting accepts values of "yes" (strict validation), "no" (no validation), or "allow-downgrade" (validate when possible but allow unvalidated responses).

"Systemd-resolved isn't just another DNS client—it's a comprehensive DNS security and performance layer that brings enterprise-grade features to every Linux system."

DNS-over-TLS (DoT) support encrypts DNS queries, preventing network observers from seeing which domains you're resolving. This privacy feature has become increasingly important as awareness of DNS surveillance grows. The DNSOverTLS setting supports three modes: "no" (disabled), "opportunistic" (use TLS when available but fall back to unencrypted), and "yes" (require TLS, failing if unavailable). Opportunistic mode provides a good balance between privacy and reliability, using encryption when upstream DNS servers support it.

Managing Systemd-Resolved Runtime Configuration

Beyond static configuration files, systemd-resolved accepts runtime configuration changes through the resolvectl command (formerly systemd-resolve). This tool allows querying current DNS configuration, testing resolution, managing per-interface DNS settings, and flushing caches. The resolvectl status command displays comprehensive information about current DNS configuration, including which DNS servers are configured for each network interface, whether DNSSEC is enabled, and cache statistics.

# Display overall DNS configuration status
resolvectl status

# Show DNS configuration for a specific interface
resolvectl status eth0

# Query a specific domain
resolvectl query example.com

# Display statistics including cache hit rate
resolvectl statistics

# Flush all cached DNS entries
resolvectl flush-caches

# Configure DNS servers for a specific interface (runtime only)
resolvectl dns eth0 8.8.8.8 1.1.1.1

# Configure search domain for an interface
resolvectl domain eth0 example.com

Runtime configuration changes made through resolvectl apply immediately but don't persist across reboots. This makes them ideal for testing DNS configurations before committing them to configuration files. For example, you might temporarily change DNS servers to troubleshoot resolution issues, then revert to original settings without editing files. The ability to configure DNS per-interface proves particularly valuable on systems with multiple network connections, allowing different DNS servers for different networks.

Systemd-Resolved Integration with NetworkManager

Modern Linux distributions often run both NetworkManager and systemd-resolved, with NetworkManager managing network connections and systemd-resolved handling DNS resolution. This integration requires proper configuration to avoid conflicts. NetworkManager can be configured to push DNS information to systemd-resolved rather than managing resolv.conf directly. This approach leverages systemd-resolved's advanced features while maintaining NetworkManager's dynamic network management.

The integration occurs through NetworkManager's dns setting in /etc/NetworkManager/NetworkManager.conf. Setting dns=systemd-resolved in the [main] section tells NetworkManager to configure DNS through systemd-resolved. NetworkManager then uses D-Bus to communicate DNS information from DHCP or static configuration to systemd-resolved, which handles actual resolution. This architecture provides the best of both systems: NetworkManager's network state awareness and systemd-resolved's advanced DNS features.

DNS Testing and Troubleshooting Tools

Effective DNS troubleshooting requires understanding and using various diagnostic tools, each providing different perspectives on the resolution process. The most fundamental tool, ping, while primarily used for connectivity testing, serves as a quick DNS functionality check. If ping can resolve a domain name to an IP address and reach the host, basic DNS functionality works. However, ping's simplicity limits its diagnostic value for complex DNS issues, as it doesn't provide detailed information about the resolution process.

The host command offers more detailed DNS information, performing straightforward DNS lookups and displaying results in a readable format. Unlike ping, host directly queries DNS servers without involving the system's full resolver stack, making it useful for testing whether DNS servers themselves function correctly. The command accepts various options for querying different record types, specifying particular DNS servers, and controlling output verbosity. For example, host -t MX example.com queries mail exchanger records, while host example.com 8.8.8.8 queries Google's DNS server specifically.

# Basic DNS lookup
host example.com

# Query specific record type
host -t MX example.com
host -t AAAA example.com

# Use a specific DNS server
host example.com 8.8.8.8

# Verbose output showing query details
host -v example.com

# Reverse DNS lookup
host 8.8.8.8

Advanced Troubleshooting with dig

The dig (Domain Information Groper) command represents the most powerful DNS troubleshooting tool available, providing exhaustive information about DNS queries and responses. Unlike simpler tools, dig displays the complete DNS transaction including query parameters, response headers, answer sections, authority sections, and additional sections. This comprehensive output enables diagnosing subtle DNS issues like incorrect TTL values, missing glue records, or misconfigured authoritative servers.

Dig's output structure follows DNS message format, making it invaluable for understanding DNS protocol details. The QUESTION section shows what was queried, the ANSWER section contains the response, the AUTHORITY section lists authoritative nameservers, and the ADDITIONAL section provides supplementary information like IP addresses for nameservers. The query statistics at the end reveal timing information, helping identify performance issues. Understanding dig output requires familiarity with DNS record types and protocol structure, but this knowledge pays dividends in troubleshooting capabilities.

  • 🔍 Basic queries: Simply running "dig example.com" performs a standard A record lookup with detailed output
  • 📊 Specific record types: Use "dig example.com MX" or "dig example.com AAAA" to query particular record types
  • 🎯 Querying specific servers: Add "@8.8.8.8" to query a particular DNS server: "dig @8.8.8.8 example.com"
  • Short output format: Add "+short" for minimal output showing just the answer: "dig +short example.com"
  • 🔄 Trace resolution path: Use "+trace" to follow the complete resolution path from root servers: "dig +trace example.com"
"Dig isn't just a troubleshooting tool—it's a window into the entire DNS infrastructure, revealing how domains resolve from root servers down to final answers."

Nslookup for Interactive DNS Queries

The nslookup command provides both interactive and non-interactive modes for DNS queries. While considered somewhat deprecated in favor of dig and host, nslookup remains widely used and available on virtually all systems. Its interactive mode allows executing multiple queries without restarting the command, making it convenient for exploratory DNS investigation. Simply running nslookup without arguments enters interactive mode, where you can query different domains, change DNS servers, and modify query parameters.

In non-interactive mode, nslookup accepts a domain name and optional DNS server as arguments, performing a single query and displaying results. The output format differs from dig, presenting information in a more user-friendly but less detailed manner. Nslookup shows the DNS server used for the query, followed by the answer. For troubleshooting, this simplicity can be advantageous when you need quick answers without parsing dig's verbose output. However, for complex DNS issues, dig's comprehensive information proves more valuable.

# Non-interactive query
nslookup example.com

# Query specific DNS server
nslookup example.com 8.8.8.8

# Query specific record type
nslookup -type=MX example.com

# Interactive mode commands
nslookup
> server 8.8.8.8          # Change DNS server
> set type=MX             # Change query type
> example.com             # Perform query
> set debug               # Enable debug output
> exit                    # Exit interactive mode

Systemd-Specific Troubleshooting

Systems using systemd-resolved require additional troubleshooting approaches beyond traditional DNS tools. The resolvectl command provides systemd-resolved-specific diagnostics, showing not just DNS configuration but also cache statistics, DNSSEC status, and per-interface settings. Running resolvectl status displays comprehensive information about current DNS configuration from systemd-resolved's perspective, often revealing discrepancies between what you configured and what's actually in use.

The systemd-resolve command (now superseded by resolvectl but still available on many systems) offers similar functionality. For troubleshooting DNSSEC issues, resolvectl query --legend=no example.com shows whether DNSSEC validation succeeded. If DNSSEC validation fails, the output indicates why, helping diagnose misconfigured DNSSEC on authoritative servers. Cache-related issues often resolve by flushing the cache with resolvectl flush-caches, forcing fresh queries to upstream DNS servers.

Examining systemd-resolved logs provides insights into resolution failures and DNSSEC validation issues. Use journalctl -u systemd-resolved -f to follow systemd-resolved logs in real-time, watching DNS queries and any errors. This proves invaluable for diagnosing intermittent issues or understanding why certain domains fail to resolve. The logs show which DNS servers are queried, whether responses are cached, DNSSEC validation results, and any errors encountered during resolution.

Local DNS Caching Solutions

Implementing local DNS caching dramatically improves resolution performance and reduces dependency on external DNS servers. A local cache stores DNS responses temporarily, serving subsequent queries for the same domains instantly without external network queries. This approach reduces latency from tens or hundreds of milliseconds to sub-millisecond response times, creating noticeably faster browsing and application performance. Beyond speed, local caching provides resilience against temporary DNS server outages and reduces bandwidth consumption.

Several caching solutions exist for Linux systems, each with different characteristics and use cases. Systemd-resolved includes built-in caching, making it the simplest option on systems already using it. The cache operates transparently, requiring no additional configuration beyond ensuring systemd-resolved is active. For more control or on systems not using systemd-resolved, dedicated caching DNS servers like dnsmasq, unbound, or BIND configured as a caching resolver provide additional features and configuration options.

Dnsmasq as a Lightweight Caching Solution

Dnsmasq represents an excellent lightweight DNS caching solution, particularly suited for workstations, small servers, and network appliances. Beyond DNS caching, dnsmasq provides DHCP server functionality and network boot support, making it versatile for various network scenarios. Its configuration simplicity and minimal resource requirements make it ideal for systems where running a full-featured DNS server would be overkill. Dnsmasq's cache operates intelligently, respecting TTL values and automatically refreshing expired entries.

Installation varies by distribution but typically involves a simple package installation: apt install dnsmasq on Debian/Ubuntu or yum install dnsmasq on Red Hat-based systems. The primary configuration file, /etc/dnsmasq.conf, contains extensive options with detailed comments explaining each setting. For basic caching functionality, minimal configuration suffices: specify upstream DNS servers with server= directives and optionally configure cache size with cache-size=. The default cache size of 150 entries works for light use, but increasing to 1000 or more benefits systems with diverse DNS queries.

# Basic dnsmasq configuration for DNS caching
# /etc/dnsmasq.conf

# Listen only on localhost
listen-address=127.0.0.1

# Upstream DNS servers
server=8.8.8.8
server=1.1.1.1

# Cache size (number of entries)
cache-size=1000

# Don't read /etc/resolv.conf for upstream servers
no-resolv

# Don't poll /etc/resolv.conf for changes
no-poll

# Log queries for debugging (disable in production)
log-queries

# Log file location
log-facility=/var/log/dnsmasq.log

After configuring dnsmasq, modify /etc/resolv.conf to point to the local cache by setting nameserver 127.0.0.1. This directs all DNS queries through dnsmasq, which serves cached responses when available or forwards queries to upstream servers for uncached domains. Remember to prevent other services from overwriting resolv.conf using methods discussed earlier. Start dnsmasq with systemctl start dnsmasq and enable it for automatic startup with systemctl enable dnsmasq.

"A local DNS cache isn't a luxury—it's a fundamental performance optimization that every system should employ, transforming DNS from a latency bottleneck into an instantaneous operation."

Unbound for Advanced Caching and Security

Unbound provides a more sophisticated caching DNS resolver with strong security features including DNSSEC validation, DNS-over-TLS support, and aggressive caching techniques. Unlike dnsmasq's simplicity, Unbound targets users wanting enterprise-grade DNS functionality with extensive configuration options. Its validating resolver capabilities perform DNSSEC validation, protecting against DNS spoofing and cache poisoning attacks. For security-conscious environments, Unbound represents an excellent choice despite its steeper learning curve.

Unbound's configuration file, /etc/unbound/unbound.conf, organizes settings into sections like server, forward-zone, and stub-zone. The server section contains general settings including interfaces to listen on, access control rules, cache sizes, and security options. For basic caching functionality, configure Unbound to listen on localhost, specify upstream DNS servers in a forward-zone, and enable DNSSEC validation. The extensive configuration options allow fine-tuning cache behavior, implementing split DNS, and enforcing security policies.

# Basic unbound configuration
# /etc/unbound/unbound.conf

server:
    # Listen on localhost only
    interface: 127.0.0.1
    
    # Access control
    access-control: 127.0.0.0/8 allow
    
    # Enable DNSSEC validation
    auto-trust-anchor-file: "/var/lib/unbound/root.key"
    
    # Cache settings
    cache-min-ttl: 300
    cache-max-ttl: 86400
    
    # Privacy settings
    hide-identity: yes
    hide-version: yes
    
    # Performance tuning
    num-threads: 2
    msg-cache-size: 8m
    rrset-cache-size: 16m

# Forward queries to upstream DNS servers
forward-zone:
    name: "."
    forward-addr: 8.8.8.8
    forward-addr: 1.1.1.1
    forward-addr: 9.9.9.9

Unbound's aggressive caching feature prefetches popular domains before their cache entries expire, ensuring frequently accessed domains always have valid cached responses. This intelligent caching reduces latency even further than basic caching, as queries never wait for upstream resolution. The cache statistics available through unbound-control stats provide visibility into cache performance, showing hit rates, query counts, and other metrics useful for optimization.

DNS Security Considerations

DNS security often receives insufficient attention despite DNS being a critical infrastructure component vulnerable to various attacks. DNS spoofing, cache poisoning, and man-in-the-middle attacks can redirect traffic to malicious servers, intercept sensitive communications, or enable phishing attacks. Understanding and implementing DNS security measures protects against these threats, ensuring that resolved IP addresses actually correspond to legitimate servers rather than attacker-controlled systems.

DNSSEC (DNS Security Extensions) provides cryptographic validation of DNS responses, creating a chain of trust from root DNS servers down to individual domain records. When properly implemented, DNSSEC prevents DNS spoofing by allowing resolvers to verify that responses come from authoritative servers and haven't been modified in transit. However, DNSSEC adoption remains incomplete, with many domains still lacking DNSSEC signatures. Enabling DNSSEC validation on your resolver provides protection for domains that implement it while falling back to traditional resolution for others.

"DNS security isn't about preventing all attacks—it's about making attacks significantly more difficult and detectable, raising the bar for adversaries while maintaining usability."

DNS-over-TLS and DNS-over-HTTPS

Traditional DNS queries transmit in cleartext, allowing network observers to see which domains you're resolving. This privacy issue enables surveillance, censorship, and targeted attacks based on DNS traffic analysis. DNS-over-TLS (DoT) and DNS-over-HTTPS (DoH) encrypt DNS queries, preventing network-level observation while maintaining DNS functionality. These protocols establish encrypted connections to DNS servers, wrapping DNS queries in TLS or HTTPS encryption.

Systemd-resolved supports DNS-over-TLS natively through the DNSOverTLS configuration option. Setting DNSOverTLS=yes in resolved.conf requires TLS for all DNS queries, while DNSOverTLS=opportunistic uses TLS when available but falls back to unencrypted DNS if necessary. Opportunistic mode provides a good balance between privacy and reliability. For DoH support, which systemd-resolved doesn't natively provide, tools like cloudflared or dnscrypt-proxy act as local proxies, accepting standard DNS queries and forwarding them via DoH to supporting servers.

# Configure systemd-resolved for DNS-over-TLS
# /etc/systemd/resolved.conf
[Resolve]
DNS=8.8.8.8 1.1.1.1
DNSOverTLS=opportunistic
DNSSEC=yes

# After configuration, restart the service
systemctl restart systemd-resolved

# Verify DoT is working
resolvectl status | grep "DNS over TLS"

Choosing Secure DNS Providers

The DNS servers you use significantly impact both privacy and security. Many ISP-provided DNS servers log queries extensively, perform DNS hijacking for advertising purposes, or lack security features like DNSSEC validation. Choosing privacy-respecting DNS providers with strong security implementations protects against these issues. Several public DNS services prioritize privacy and security, offering DNSSEC validation, DoT/DoH support, and minimal logging policies.

Cloudflare DNS (1.1.1.1) emphasizes privacy with a commitment to purge logs within 24 hours and never sell user data. It supports both DoT and DoH, provides DNSSEC validation, and offers excellent performance with global infrastructure. Google Public DNS (8.8.8.8) provides robust DNSSEC support and high reliability, though privacy-conscious users may prefer alternatives given Google's data collection practices. Quad9 (9.9.9.9) adds security-focused features like blocking known malicious domains based on threat intelligence feeds, providing an additional security layer.

  • 🛡️ DNSSEC support: Essential for validating DNS responses and preventing spoofing attacks
  • 🔐 DoT/DoH availability: Enables encrypted DNS queries preventing network surveillance
  • 📊 Logging policies: Minimal logging protects privacy; detailed policies should be reviewed
  • Performance and reliability: Low latency and high availability ensure good user experience
  • 🌍 Geographic distribution: Global infrastructure reduces latency through nearby servers

Implementing Split DNS for Internal Resources

Organizations often need split DNS configurations where internal domain names resolve to private IP addresses while external queries use public DNS servers. This architecture allows using the same domain names internally and externally with different IP addresses, maintaining security by not exposing internal infrastructure details publicly. Implementing split DNS requires configuring your DNS resolver to query different DNS servers based on the domain being resolved.

Systemd-resolved supports split DNS through per-interface domain configuration, allowing you to specify that certain domains should resolve through particular DNS servers. Dnsmasq and Unbound offer similar capabilities through their configuration files. For example, you might configure internal.example.com to resolve through corporate DNS servers at 10.0.0.1 while all other queries use public DNS servers. This configuration ensures internal resources remain accessible while maintaining external connectivity.

Common DNS Configuration Issues and Solutions

DNS configuration problems manifest in various ways, from complete inability to resolve any domain names to subtle issues where only certain domains fail resolution. Systematic troubleshooting begins with verifying basic network connectivity—if you can ping IP addresses but not domain names, DNS is likely the culprit. However, if even IP addresses are unreachable, the problem lies elsewhere in network configuration. Understanding common failure patterns helps quickly identify and resolve DNS issues.

Resolv.conf Being Overwritten

One of the most frequent frustrations involves carefully configured DNS settings in /etc/resolv.conf being overwritten by DHCP clients, NetworkManager, or other services. This issue typically occurs after network changes, system reboots, or service restarts. The solution depends on identifying which service is overwriting the file and either configuring that service appropriately or preventing it from managing DNS.

Check if resolv.conf is a symbolic link by running ls -l /etc/resolv.conf. If it links to /run/systemd/resolve/stub-resolv.conf or /run/NetworkManager/resolv.conf, systemd-resolved or NetworkManager manages DNS. In these cases, configure DNS through the appropriate service rather than editing resolv.conf directly. If you need manual control, break the symbolic link with rm /etc/resolv.conf, create a new regular file, and protect it with chattr +i /etc/resolv.conf to prevent overwrites.

Slow DNS Resolution

Slow DNS resolution creates frustrating delays when accessing websites or services. This issue often stems from unreachable or slow-responding DNS servers, lack of local caching, or misconfigured timeout values. Testing resolution speed with time dig example.com reveals how long queries take. If queries consistently take several seconds, DNS servers may be geographically distant, overloaded, or experiencing network issues.

Solutions include switching to faster DNS servers, implementing local DNS caching with dnsmasq or systemd-resolved, and adjusting resolver timeout values. The resolv.conf options timeout and attempts control how long to wait for responses and how many retries to perform. Reducing timeout values speeds up failure detection but may cause premature timeouts on slow networks. Implementing local caching provides the most dramatic improvement, reducing resolution time to nearly zero for cached domains.

"Most DNS problems aren't actually DNS problems—they're configuration management problems where automated systems fight manual changes, creating an endless cycle of frustration."

DNSSEC Validation Failures

DNSSEC validation failures prevent resolution of domains with misconfigured DNSSEC, showing symptoms like domains being unreachable despite working from other networks or systems. These issues often affect specific domains while others resolve normally. Testing DNSSEC with dig +dnssec example.com shows whether DNSSEC records exist and validate correctly. If validation fails, either the domain's DNSSEC is misconfigured or your resolver's DNSSEC validation is too strict.

For systemd-resolved, check DNSSEC status with resolvectl query example.com, which indicates whether DNSSEC validation succeeded. If legitimate domains fail DNSSEC validation due to resolver issues, temporarily disabling DNSSEC with DNSSEC=no in resolved.conf may be necessary. However, this removes DNSSEC protection, so investigate the root cause rather than permanently disabling validation. Often, updating trust anchors or adjusting DNSSEC settings resolves the issue without completely disabling validation.

IPv6 DNS Issues

IPv6 DNS configuration introduces additional complexity, particularly in dual-stack environments with both IPv4 and IPv6 connectivity. Issues include IPv6 DNS servers being unreachable, applications preferring IPv6 but DNS only configured for IPv4, or AAAA record queries failing while A records succeed. These problems often manifest as intermittent failures or performance issues rather than complete resolution failure.

Verify IPv6 DNS configuration with resolvectl status or by examining resolv.conf for IPv6 nameserver addresses. Test IPv6 DNS resolution specifically with dig AAAA example.com or host -t AAAA example.com. If IPv6 DNS servers are configured but unreachable, either remove them from configuration or fix IPv6 connectivity. In environments without working IPv6, disabling IPv6 DNS queries through resolver options prevents unnecessary delays from IPv6 query attempts.

Best Practices for DNS Configuration

Implementing DNS configuration best practices ensures reliable, secure, and performant name resolution while minimizing troubleshooting needs. These practices apply across different Linux distributions and DNS management approaches, providing a foundation for robust DNS infrastructure. Following established patterns prevents common pitfalls and creates consistent, maintainable configurations.

Configure Multiple DNS Servers

Always configure at least two DNS servers, preferably three, to provide redundancy when primary servers become unreachable. This redundancy ensures continued name resolution during DNS server outages, maintenance, or network issues. Choose DNS servers from different providers and geographic locations to avoid single points of failure. For example, combining Cloudflare (1.1.1.1), Google (8.8.8.8), and Quad9 (9.9.9.9) provides diversity across providers and infrastructure.

The resolver queries DNS servers in the order listed, so place the fastest or most reliable server first. However, the rotate option distributes queries across all configured servers, improving load distribution and resilience. This option particularly benefits environments with multiple DNS queries, preventing the first server from becoming a bottleneck. Be aware that some resolvers limit the number of nameservers they'll use, typically three, so additional entries may be ignored.

Implement Local DNS Caching

Local DNS caching dramatically improves performance and reduces dependency on external DNS infrastructure. Whether using systemd-resolved's built-in caching, dnsmasq, or Unbound, implementing a local cache should be standard practice on all systems. The performance benefits extend beyond faster browsing to improved application responsiveness, reduced network traffic, and better resilience against temporary DNS outages.

Monitor cache performance through available statistics to ensure it's functioning effectively. For systemd-resolved, resolvectl statistics shows cache hit rates. For dnsmasq, enabling logging reveals cache behavior. High cache hit rates (above 50%) indicate effective caching, while low hit rates suggest cache size may be too small or TTL values too short. Adjust cache sizes based on usage patterns—systems with diverse DNS queries benefit from larger caches.

Enable DNSSEC Validation

DNSSEC validation should be enabled wherever possible to protect against DNS spoofing and cache poisoning attacks. Modern DNS resolvers including systemd-resolved, Unbound, and BIND support DNSSEC validation with minimal configuration. While not all domains implement DNSSEC, validating those that do provides significant security benefits without breaking resolution for domains lacking DNSSEC.

Use permissive DNSSEC modes like systemd-resolved's allow-downgrade setting, which validates DNSSEC when available but allows unvalidated responses for domains without DNSSEC. This approach provides security benefits without causing resolution failures for non-DNSSEC domains. Monitor DNSSEC validation through resolver logs to identify domains with DNSSEC issues, which may indicate either misconfiguration or potential attacks.

"DNS configuration best practices aren't about following rules—they're about building resilient systems that continue functioning when individual components fail, attacks occur, or conditions change."

Document Configuration Choices

Maintain documentation explaining your DNS configuration choices, including which DNS servers are used and why, what management system controls DNS (NetworkManager, systemd-resolved, manual), and any special configurations like split DNS or custom resolver options. This documentation proves invaluable when troubleshooting issues months or years later, during staff transitions, or when auditing security configurations.

Include configuration file locations, commands for viewing current settings, and procedures for making changes in your documentation. For automated environments, document configuration management code and the reasoning behind specific choices. This documentation should live with other system documentation, making it accessible to anyone maintaining the system. Consider adding comments directly in configuration files explaining non-obvious settings.

Test Configuration Changes Thoroughly

Always test DNS configuration changes before deploying them broadly, especially in production environments. Use testing tools like dig, host, and resolvectl to verify that changes produce expected results. Test both successful resolution of valid domains and proper failure behavior for nonexistent domains. Verify that all configured DNS servers respond correctly and that fallback mechanisms work when primary servers are unavailable.

For systemd-resolved, runtime configuration changes through resolvectl allow testing without modifying configuration files. This enables safe experimentation—if changes cause problems, simply restart systemd-resolved to revert to file-based configuration. Similarly, NetworkManager's nmcli commands can test DNS changes on specific connections without affecting others. Only commit changes to configuration files after verifying they work as intended.

Frequently Asked Questions

How do I check which DNS servers my Linux system is currently using?

The method depends on your DNS management system. For systemd-resolved, run resolvectl status to see configured DNS servers per interface. On systems using traditional resolv.conf, examine cat /etc/resolv.conf to see nameserver entries. For NetworkManager-managed systems, use nmcli dev show to display DNS configuration for each network device. You can also test which DNS server actually responds to queries by running dig example.com and examining the "SERVER" line in the output, which shows the DNS server that answered the query.

Why does my /etc/resolv.conf keep getting overwritten after I edit it?

This occurs because automated network management services like NetworkManager, systemd-resolved, or DHCP clients manage resolv.conf dynamically. These services update DNS configuration based on network connections, DHCP responses, or their own configuration files. Check if resolv.conf is a symbolic link with ls -l /etc/resolv.conf—if it points to files in /run/, an automated service controls it. Solutions include configuring DNS through the managing service (nmcli for NetworkManager, resolved.conf for systemd-resolved), making the file immutable with chattr +i /etc/resolv.conf, or configuring DHCP clients to ignore DNS information from DHCP servers.

What's the difference between DNS and domain in /etc/resolv.conf?

The search directive accepts multiple domain names that are automatically appended to unqualified hostnames during resolution, allowing you to specify "server1" and have it automatically try "server1.example.com" and "server1.corp.local" based on your search list. The domain directive specifies only a single local domain name and is older, largely superseded by the more flexible search directive. In practice, most modern configurations use search rather than domain. If both are present, the last one in the file takes precedence. Search domains are particularly useful in corporate environments where internal resources use consistent domain naming.

How can I improve DNS resolution speed on my Linux system?

Implementing local DNS caching provides the most significant performance improvement, reducing resolution time from tens or hundreds of milliseconds to under a millisecond for cached entries. Enable systemd-resolved caching if available, or install dnsmasq or Unbound as dedicated caching resolvers. Additionally, choose geographically nearby DNS servers with good performance—test different providers with time dig example.com @8.8.8.8 to measure response times. Consider using DNS servers that support DNS-over-TLS or DNS-over-HTTPS, which some providers optimize for performance. Finally, adjust resolver timeout values in resolv.conf to fail faster on unresponsive servers, though be careful not to set timeouts too low for slow networks.

Is it safe to use public DNS servers like Google or Cloudflare instead of my ISP's DNS?

Public DNS servers from reputable providers often offer better security, privacy, and performance than ISP-provided DNS servers. Major providers like Cloudflare, Google, and Quad9 implement DNSSEC validation, provide DoT/DoH encryption options, and maintain high-performance global infrastructure. However, consider privacy implications—some providers log queries more extensively than others. Cloudflare emphasizes privacy with minimal logging, while Google's privacy policy may concern some users. ISP DNS servers may perform better for ISP-hosted content due to geographic proximity and CDN integration. For maximum privacy, consider running your own recursive DNS resolver, though this requires more technical knowledge and maintenance. Using multiple DNS providers from different organizations provides both redundancy and reduces dependence on any single provider.

How do I configure DNS to use different servers for different domains (split DNS)?

Split DNS configuration methods vary by DNS management system. For systemd-resolved, use resolvectl domain INTERFACE DOMAIN combined with resolvectl dns INTERFACE DNS_SERVERS to specify that certain domains resolve through specific DNS servers. In resolved.conf, configure Domains with tilde prefix like Domains=~internal.example.com to route those queries to specific DNS servers. For dnsmasq, use server=/internal.example.com/10.0.0.1 to direct queries for internal.example.com to the specified DNS server. Unbound supports similar configuration through stub-zone or forward-zone sections specifying domain names and corresponding DNS servers. NetworkManager can configure per-connection DNS settings that effectively implement split DNS when combined with connection-specific routing.

What should I do if DNSSEC validation is breaking access to legitimate websites?

DNSSEC validation failures for legitimate websites typically indicate misconfigured DNSSEC on the authoritative DNS servers rather than issues with your resolver. First, verify the problem is actually DNSSEC-related by testing with dig +dnssec example.com and checking for validation errors. Try accessing the domain from another network or device—if it works elsewhere, your resolver configuration may be too strict. For systemd-resolved, check validation status with resolvectl query example.com. If DNSSEC is genuinely misconfigured on the domain, you can temporarily disable validation for specific domains or globally, though this removes security benefits. Report DNSSEC issues to domain administrators so they can fix their configuration. Consider using DNSSEC validation mode "allow-downgrade" rather than strict validation, which validates when possible but allows unvalidated responses when necessary.

How do I configure DNS servers permanently on a system using NetworkManager?

NetworkManager stores connection configurations that persist across reboots, making DNS configuration through NetworkManager inherently permanent. Use nmcli con mod "CONNECTION_NAME" ipv4.dns "8.8.8.8 1.1.1.1" to set DNS servers for a specific connection, replacing CONNECTION_NAME with your actual connection name from nmcli con show. Add ipv4.ignore-auto-dns yes to prevent DHCP from overriding your settings: nmcli con mod "CONNECTION_NAME" ipv4.ignore-auto-dns yes. After modification, restart the connection with nmcli con down "CONNECTION_NAME" && nmcli con up "CONNECTION_NAME" to apply changes. These settings are stored in /etc/NetworkManager/system-connections/ and persist across reboots. For IPv6 DNS, use similar commands with ipv6.dns and ipv6.ignore-auto-dns.