终于解决 k8s 集群中部署 nodelocaldns 的问题

自从开始在 kubernetes 集群中部署 nodelocaldns 以提高 dns 解析性能以来,一直被一个问题困扰,只要一部署 nodelocaldns ,在 coredns 中添加的 rewrite 与 hosts 配置(如下)就失效,很是郁闷。

rewrite stop {
    name regex ([a-zA-Z0-9-]+)_([a-zA-Z0-9-]+)\.$ {1}-{2}.production.svc.cluster.local
    answer name ([a-zA-Z0-9-]+)-([a-zA-Z0-9-]+)\.production\.svc\.cluster\.local\.$ {1}_{2}
}
hosts {
    10.0.78.124   memcached
    ....
    fallthrough
}

部署使用的是下面的命令,在部署时将 nodelocaldns.yaml 中的几个变量进行如下的替换。

sed 's/k8s.gcr.io/gcr.azk8s.cn\/google_containers/g
s/__PILLAR__DNS__SERVER__/10.96.0.10/g
s/__PILLAR__LOCAL__DNS__/169.254.20.10/g
s/__PILLAR__DNS__DOMAIN__/cluster.local/g' nodelocaldns.yaml |
kubectl apply -n kube-system -f -

部署后其他解析都正常,就是与 rewrite 与 hosts 配置相关的解析总是失败。

后来尝试直接在 node-local-dns 中配置 rewrite 与 hosts ,结果发现 nodelocaldns 镜像集成的 coredns 版本不支持这 2 个插件(plugin),更是郁闷。

在准备放弃之前,今天再次尝试解决这个问题,终于在 github 上一个 issue 的回复中找到了解决方法,详见 plugin/rewrite Not working in k8s

原来问题是 .:53 部分的 forward 配置引起的。

进入 nodelocaldns 容器 cat /etc/Corefile 命令查看 .:53 部分的 forward 配置是 /etc/resolv.conf ,根本没有转发给集群的 coredns ,难怪 rewrite 与 hosts 的配置不起作用。

.:53 {
    errors
    cache 30
    reload
    loop
    bind 169.254.20.10 10.96.0.10
    forward . /etc/resolv.conf {
            force_tcp
    }
    prometheus :9253
}

在 nodelocaldns.yaml 中这里的 forward 配置对应的是一个变量 __PILLAR__UPSTREAM__SERVERS__

forward . __PILLAR__UPSTREAM__SERVERS__ {
        force_tcp
}

这个变量值是在部署 node-local-dns 时自动设置的。

The following variables will be set by the node-cache images - k8s.gcr.io/k8s-dns-node-cache:1.15.6 or later. The values will be determined by reading the kube-dns configMap for custom Upstream server configuration.

只要将 __PILLAR__UPSTREAM__SERVERS__ 改为 kube-dns-upstream service 的 IP 地址(比如这里是10.96.53.196)就能解决问题。

查看 kube-dns-upstream service IP 地址的命令:

kubectl get svc -n kube-system | grep kube-dns-upstream

改进后的部署命令:

sed 's/k8s.gcr.io/gcr.azk8s.cn\/google_containers/g
s/__PILLAR__DNS__SERVER__/10.96.0.10/g
s/__PILLAR__LOCAL__DNS__/169.254.20.10/g
s/__PILLAR__UPSTREAM__SERVERS__/10.96.53.196/g
s/__PILLAR__DNS__DOMAIN__/cluster.local/g' nodelocaldns.yaml |
kubectl apply -n kube-system -f -

终于搞定!

2022-02-03 更新:gcr.azk8s.cn 已经不能访问,需要改为 registry.aliyuncs.com

posted @ 2020-01-11 21:03  dudu  阅读(10576)  评论(4编辑  收藏  举报