2.4.4 DNS客户端配置与缓存管理

DNS客户端配置与缓存管理#

DNS客户端负责将域名解析为IP地址。Linux通过/etc/nsswitch.conf决定解析顺序,并由/etc/hosts/etc/resolv.conf与本地缓存服务共同完成解析。本节给出原理草图、配置示例、安装启用、排错步骤与练习。

1. 原理草图与解析顺序#

文章图片
# /etc/nsswitch.conf
hosts: files dns
# 说明:优先读取 /etc/hosts,再走DNS查询

2. /etc/resolv.conf 关键参数与示例#

# /etc/resolv.conf
nameserver 223.5.5.5
nameserver 8.8.8.8
search example.com
options timeout:2 attempts:3 rotate ndots:1
  • nameserver:DNS服务器地址,建议不超过3条。
  • search:短主机名自动补全域。
  • timeout/attempts:超时与重试次数。
  • rotate:轮询使用多个DNS。
  • ndots:点数小于该值时优先补search域。

验证解析路径:

# 解析顺序验证:/etc/hosts优先
echo "1.2.3.4 test.local" | sudo tee -a /etc/hosts
getent hosts test.local
# 预期输出:1.2.3.4 test.local

3. 常见DNS缓存服务:安装、启用与配置#

3.1 systemd-resolved(多数发行版默认)

# 查看状态与缓存统计
systemctl status systemd-resolved
resolvectl statistics

# 查询解析结果
resolvectl query www.example.com

# 刷新缓存
resolvectl flush-caches
# /etc/systemd/resolved.conf
[Resolve]
DNS=223.5.5.5 8.8.8.8
FallbackDNS=1.1.1.1
DNSStubListener=yes
# 让 /etc/resolv.conf 指向systemd-resolved的stub
sudo ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
systemctl restart systemd-resolved

3.2 nscd(轻量缓存)

# 安装(Debian/Ubuntu)
sudo apt-get update && sudo apt-get install -y nscd

# 安装(RHEL/CentOS)
sudo yum install -y nscd

# 启动与自启
sudo systemctl enable --now nscd
# /etc/nscd.conf(关键片段)
enable-cache hosts yes
positive-time-to-live hosts 600
negative-time-to-live hosts 20
# 使hosts缓存失效
sudo nscd -i hosts

3.3 dnsmasq(本地缓存与转发)

# 安装
sudo apt-get install -y dnsmasq   # Debian/Ubuntu
sudo yum install -y dnsmasq       # RHEL/CentOS

# 启动与自启
sudo systemctl enable --now dnsmasq
# /etc/dnsmasq.conf(示例)
port=53
cache-size=1000
server=223.5.5.5
server=8.8.8.8
# 让系统使用本地dnsmasq
echo -e "nameserver 127.0.0.1\noptions timeout:2 attempts:2" | sudo tee /etc/resolv.conf
systemctl restart dnsmasq

4. NetworkManager / DHCP 覆盖控制#

# 查看当前连接名
nmcli con show

# 设置静态DNS并关闭自动DNS
nmcli con mod "ens33" ipv4.dns "223.5.5.5 8.8.8.8"
nmcli con mod "ens33" ipv4.ignore-auto-dns yes
nmcli con up "ens33"

5. 排错流程(含命令解释)#

# 1) 查看解析链路与系统配置
cat /etc/nsswitch.conf
cat /etc/hosts
cat /etc/resolv.conf

# 2) 直接对上游DNS发起解析
dig @223.5.5.5 www.example.com +time=2 +tries=1
# +time=2 单次超时2秒;+tries=1 仅重试1次

# 3) 查询解析结果(走系统解析器)
getent hosts www.example.com

# 4) 判断本地缓存影响
resolvectl statistics
resolvectl flush-caches

# 5) 排查覆盖来源
ls -l /etc/resolv.conf
# 若为符号链接,确认指向的文件是否被NetworkManager/systemd-resolved管理

常见故障与处理要点:
- 解析慢:DNS不可达/超时设置过大/缓存命中低。验证dig @DNS延迟并调小timeout
- 解析错误/etc/hosts覆盖旧记录,或DNS记录未更新。优先检查本地静态映射。
- 解析失败resolv.conf被DHCP覆盖,使用nmcli关闭自动DNS。

6. 练习(动手验证)#

  1. 本地优先解析
    test.local写入/etc/hosts并用getent验证优先级。
  2. 对比缓存前后解析时延
    使用dig对同一域名连续查询3次,记录时延;启用dnsmasq后对比。
  3. 模拟DNS不可达
    resolv.conf中首个nameserver改为不可达IP,观察dig超时与attempts效果。
  4. 排除覆盖问题
    使用nmcli设置静态DNS并重启连接,确认/etc/resolv.conf不再被DHCP重写。