骏骏的运维小窝

如果在CoreDNS中添加自定义解析域

2026/01/14
3
0

本文介绍了如何通过修改CoreDNS的方式为Kubernetes服务添加一个解析域。



在Kubernetes中, Coredns中如果未找到域名解析,会向在上游宿主机发起寻址。

有一种情况,某些域名只存在于特定的DNS服务器中而非Kubernetes宿主机上,这时候需要将特定的域名解析转到指定的DNS服务器中。

该方法的实现可以通过修改CoreDNS来实现。



解决方案

确认CoreDNS配置文件存在:

kubectl get configmap coredns -n kube-system

修改CoreDNS配置文件,修改对应的data段

kubectl edit configmap coredns -n kube-system

data:
  Corefile: |
    .:53 {
        errors
        health {
          lameduck 5s
        }
        ready
        kubernetes cluster.local 10.254.0.0/16 {
          fallthrough in-addr.arpa ip6.arpa
        }
        prometheus :9153
        forward . /etc/resolv.conf
        cache 30
        loop
        reload
        loadbalance
    }

    api.service.xxx.cn:53 {
        errors
        cache 30
        forward . 10.23.255.1 10.23.255.2 {
            max_concurrent 1000
            health_check 5s
        }
        log
    }

修改过的文件有可能会有格式问题,需要修复:

cat > fix-coredns.yaml << 'EOF'
apiVersion: v1
data:
  Corefile: |
    .:53 {
        errors
        health {
          lameduck 5s
        }
        ready
        kubernetes cluster.local 10.254.0.0/16 {
          fallthrough in-addr.arpa ip6.arpa
        }
        prometheus :9153
        forward . /etc/resolv.conf
        cache 30
        loop
        reload
        loadbalance
    }
    
    api.service.xxx.cn:53 {
        errors
        cache 30
        forward . 10.23.255.1 10.23.255.2 {
            max_concurrent 1000
            health_check 5s
        }
        log
    }
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
EOF

应用CoreDNS配置:

kubectl apply -f fix-coredn

重启CoreDNS服务:

kubectl rollout restart deployment coredns -n kube-system