如何让EC2通过dnsmasq本地缓存,EKS采用NodeLocalDNS进行?
摘要:# DNS 缓存配置指南 > EC2 使用 dnsmasq 本地缓存 + EKS 使用 NodeLocalDNS ## 目录 - [一、EC2 使用本地 DNS 缓存](#一ec2-使用本地-dns-
# DNS 缓存配置指南
> EC2 使用 dnsmasq 本地缓存 + EKS 使用 NodeLocalDNS
---
## 目录
- [一、EC2 使用本地 DNS 缓存](#一ec2-使用本地-dns-缓存)
- [二、EKS 使用 NodeLocalDNS](#二eks-使用-nodelocaldns)
- [三、最佳实践](#三最佳实践)
---
## 一、EC2 使用本地 DNS 缓存
### 1.1 Ubuntu 系统配置
#### 安装 dnsmasq
```bash
# 安装 dnsmasq
apt install dnsmasq -y
# 创建用户组
groupadd -r dnsmasq
usermod -g dnsmasq dnsmasq
```
#### 配置 dnsmasq
```bash
# 备份原配置
mv /etc/dnsmasq.conf /etc/dnsmasq.conf.ori
# 编辑新配置
vim /etc/dnsmasq.conf
```
**dnsmasq.conf 配置内容**:
```ini
# 监听地址
listen-address=127.0.0.1
# 缓存大小
cache-size=1000
# 上游 DNS 服务器(AWS 内网 DNS 地址)
server=10.19.0.2
# 忽略 /etc/resolv.conf,防止循环解析
no-resolv
# 可选:记录查询日志(调试时用)
log-queries
log-facility=/var/log/dnsmasq.log
```
#### 配置系统 DNS
```bash
# 停止 systemd-resolved
systemctl stop systemd-resolved
systemctl disable systemd-resolved
# 备份 resolv.conf
mv /etc/resolv.conf /etc/resolv.conf.bak
# 配置使用本地 DNS
echo "nameserver 127.0.0.1" | tee /etc/resolv.conf
# 启动并启用 dnsmasq
systemctl restart dnsmasq
systemctl enable dnsmasq
```
#### 配置日志滚动
```bash
# 创建日志滚动配置
vim /etc/logrotate.d/dnsmasq
```
**logrotate 配置内容**:
```
/var/log/dnsmasq.log {
daily
rotate 3
missingok
notifempty
compress
delaycompress
create 0640
su root adm
copytruncate
}
```
### 1.2 Amazon Linux 系统
参考 AWS 官方文档:
> https://repost.aws/zh-Hans/knowledge-center/dns-resolution-failures-ec2-linux
### 1.3 验证 DNS 缓存
```bash
# 首次查询(无缓存)
time dig example.com
# 再次查询(有缓存,应该更快)
time dig example.com
# 查看缓存统计
kill -USR1 $(pidof dnsmasq)
cat /var/log/dnsmasq.log | grep "cache"
```
---
## 二、EKS 使用 NodeLocalDNS
### 2.1 概述
NodeLocalDNS 通过在每个节点上运行 DNS 缓存代理来提高集群 DNS 性能。
