Akemi

ubuntu设置k8s dns解析

2025/10/21

在使用kubespray安装k8s时,k8s安装过程中会自动将域名解析信息写入/etc/resolv.conf

但如果使用较新版本的ubuntu安装,由于ubuntu的dns解析是通过systemd-resolved管理的,会导致使用hostNetwork模式的pod无法通过k8s集群内部域名,比如mysql-headless.prod.svc.cluster.local:8080这样的方式来访问服务

因为

同样的,也有一些类RHEL的系统就算不使用systemd-resolved,也会使用NetworkManager来管理dns解析

所以这篇就记录下如何修改dns,使其可以适应k8s的dns

systemd-resolved

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
cat /etc/resolv.conf 
# This file is managed by man:systemd-resolved(8). Do not edit.
#
# This is a dynamic resolv.conf file for connecting local clients to the
# internal DNS stub resolver of systemd-resolved. This file lists all
# configured search domains.
#
# Run "resolvectl status" to see details about the uplink DNS servers
# currently in use.
#
# Third party programs must not access this file directly, but only through the
# symlink at /etc/resolv.conf. To manage man:resolv.conf(5) in a different way,
# replace this symlink by a static file or a different symlink.
#
# See man:systemd-resolved.service(8) for details about the supported modes of
# operation for /etc/resolv.conf.

nameserver 127.0.0.53
options edns0 trust-ad

修改dns

1
2
3
4
5
6
7
8
9
10
kubectl get svc -n kube-system kube-dns
一般是10.96.0.10

sudo mkdir -p /etc/systemd/resolved.conf.d/
sudo tee /etc/systemd/resolved.conf.d/k8s.conf > /dev/null <<EOF
[Resolve]
DNS=10.96.0.10
Domains=~cluster.local
EOF
sudo systemctl restart systemd-resolved

NetworkManager

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 1. 启用并启动 systemd-resolved
sudo systemctl enable systemd-resolved
sudo systemctl start systemd-resolved

# 2. 配置 NetworkManager 使用 systemd-resolved
sudo tee /etc/NetworkManager/conf.d/k8s-resolved.conf > /dev/null <<EOF
[main]
dns=systemd-resolved
EOF

# 3. 配置 systemd-resolved 的 DNS 转发
sudo mkdir -p /etc/systemd/resolved.conf.d/
sudo tee /etc/systemd/resolved.conf.d/k8s.conf > /dev/null <<EOF
[Resolve]
DNS=10.96.0.10
Domains=cluster.local svc.cluster.local default.svc.cluster.local
EOF

# 4. 重启服务
sudo systemctl restart systemd-resolved
sudo systemctl restart NetworkManager

CATALOG
  1. 1. systemd-resolved
  2. 2. NetworkManager