DNS with dnsmasq

dnsmasq is a lightweight, easy-to-configure DNS forwarder and DHCP server. It is ideal for small networks, development environments, and as a local resolver with custom host mappings and caching.

Key Features

  • DNS forwarding: Forwards queries to upstream DNS servers (e.g., Cloudflare, Google DNS).
  • Local DNS: Provides DNS for local hostnames without a full authoritative server.
  • DHCP server: Can assign IP addresses on the local network.
  • TFTP server: Supports network booting (PXE).
  • DNS caching: Caches responses to speed up repeated queries.
  • Reads /etc/hosts: Automatically uses local host file entries.

Installation

apt install dnsmasq       # Debian/Ubuntu
dnf install dnsmasq       # Fedora/RHEL
pacman -S dnsmasq         # Arch

Configuration

The main configuration file is /etc/dnsmasq.conf, with additional files in /etc/dnsmasq.d/.

Basic DNS Forwarding

# /etc/dnsmasq.d/forwarding.conf
no-resolv                    # Ignore /etc/resolv.conf
server=1.1.1.1              # Upstream DNS
server=8.8.8.8              # Backup upstream
cache-size=1000             # DNS cache size

Local Hostnames

Add local hostnames in /etc/hosts or in a dedicated dnsmasq hosts file:

# /etc/hosts
192.168.1.10  server.local  server
192.168.1.20  laptop.local  laptop

Or use an explicit hosts file:

# /etc/dnsmasq.d/hosts.conf
addn-hosts=/etc/dnsmasq.hosts

DHCP Server

dnsmasq can act as a DHCP server:

# /etc/dnsmasq.d/dhcp.conf
interface=eth0              # Listen on eth0
dhcp-range=192.168.1.50,192.168.1.150,12h
dhcp-option=3,192.168.1.1   # Gateway
dhcp-option=6,192.168.1.10  # DNS server

Wildcard DNS

Provide DNS for all subdomains of a local domain:

address=/local.lan/192.168.1.10

Query Logging

Log all DNS queries for debugging:

log-queries                  # Log all queries
log-facility=/var/log/dnsmasq.log

Systemd Integration

Enable and start dnsmasq:

systemctl enable --now dnsmasq

To use dnsmasq as the system resolver, configure your network manager to use 127.0.0.1 as the nameserver, or update /etc/resolv.conf:

nameserver 127.0.0.1

Common Use Cases

  • Local development: Map myapp.test to 127.0.0.1 for local web development.
  • Ad blocking: Add blocklists to prevent resolution of ad domains.
  • Split DNS: Resolve internal names locally while forwarding external queries.
  • Network boot: Serve DHCP and TFTP for PXE booting diskless workstations.

Debugging

Check the dnsmasq configuration:

dnsmasq --test

Query the local resolver:

dig @127.0.0.1 example.com
dig @127.0.0.1 -x 192.168.1.1

View logs:

journalctl -u dnsmasq
tail -f /var/log/dnsmasq.log