kubernetes1.11版本开始,kubernetes集群内部的DNS解析主要由coredns完成

kubelet中指定DNS解析地址

kubelet-config.yml中添加配置

clusterDNS:  # DNS服务的clusterIP
- 11.0.0.2
clusterDomain: cluster.local  # 在DNS服务中设置的域名

部署coredns服务

yaml文件:

apiVersion: v1
kind: ServiceAccount
metadata:
  name: coredns
  namespace: kube-system
  labels:
      kubernetes.io/cluster-service: "true"
      addonmanager.kubernetes.io/mode: Reconcile
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
    addonmanager.kubernetes.io/mode: Reconcile
  name: system:coredns
rules:
- apiGroups:
  - ""
  resources:
  - endpoints
  - services
  - pods
  - namespaces
  verbs:
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - nodes
  verbs:
  - get
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  annotations:
    rbac.authorization.kubernetes.io/autoupdate: "true"
  labels:
    kubernetes.io/bootstrapping: rbac-defaults
    addonmanager.kubernetes.io/mode: EnsureExists
  name: system:coredns
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:coredns
subjects:
- kind: ServiceAccount
  name: coredns
  namespace: kube-system
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns
  namespace: kube-system
  labels:
      addonmanager.kubernetes.io/mode: EnsureExists
data:
  Corefile: |
    .:53 {
        errors
        health
        ready
        kubernetes cluster.local in-addr.arpa ip6.arpa {  # cluster.local为指定的域名,与kubelet中配置的clusterDomain要一致
            pods insecure
            fallthrough in-addr.arpa ip6.arpa
            ttl 30
        }
        prometheus :9153
        forward . /etc/resolv.conf
        cache 30
        loop
        reload
        loadbalance
    }
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: coredns
  namespace: kube-system
  labels:
    k8s-app: kube-dns
    kubernetes.io/cluster-service: "true"
    addonmanager.kubernetes.io/mode: Reconcile
    kubernetes.io/name: "CoreDNS"
spec:
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
  selector:
    matchLabels:
      k8s-app: kube-dns
  template:
    metadata:
      labels:
        k8s-app: kube-dns
      annotations:
        seccomp.security.alpha.kubernetes.io/pod: 'docker/default'
    spec:
      priorityClassName: system-cluster-critical
      serviceAccountName: coredns
      tolerations:
        - key: "CriticalAddonsOnly"
          operator: "Exists"
      nodeSelector:
        beta.kubernetes.io/os: linux  # 选择Linux操作系统部署
      containers:
      - name: coredns
        image: coredns/coredns:1.6.1
        imagePullPolicy: IfNotPresent
        resources:
          limits:
            memory: 512Mi
          requests:
            cpu: 100m
            memory: 70Mi
        args: [ "-conf", "/etc/coredns/Corefile" ]
        volumeMounts:
        - name: config-volume
          mountPath: /etc/coredns
          readOnly: true
        - name: date-config
          mountPath: /etc/localtime
        ports:
        - containerPort: 53
          name: dns
          protocol: UDP
        - containerPort: 53
          name: dns-tcp
          protocol: TCP
        - containerPort: 9153
          name: metrics
          protocol: TCP
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 180
          timeoutSeconds: 10
          successThreshold: 1
          failureThreshold: 5
        readinessProbe:
          httpGet:
            path: /ready
            port: 8181
            scheme: HTTP
        securityContext:
          allowPrivilegeEscalation: false
          capabilities:
            add:
            - NET_BIND_SERVICE
            drop:
            - all
          readOnlyRootFilesystem: true
      dnsPolicy: Default
      volumes:
        - name: config-volume
          configMap:
            name: coredns
            items:
            - key: Corefile
              path: Corefile
        - name: date-config
          hostPath:
            path: /usr/share/zoneinfo/Asia/Shanghai 
---
apiVersion: v1
kind: Service
metadata:
  name: kube-dns
  namespace: kube-system
  annotations:
    prometheus.io/port: "9153"
    prometheus.io/scrape: "true"
  labels:
    k8s-app: kube-dns
    kubernetes.io/cluster-service: "true"
    addonmanager.kubernetes.io/mode: Reconcile
    kubernetes.io/name: "CoreDNS"
spec:
  selector:
    k8s-app: kube-dns
  clusterIP: 11.0.0.2  # 指定service的clusterIP,与kubelet中配置的要一值
  ports:
  - name: dns
    port: 53
    protocol: UDP
  - name: dns-tcp
    port: 53
    protocol: TCP
  - name: metrics
    port: 9153
    protocol: TCP

coredns的配置说明

coredns的主要功能是通过插件系统实现的。coredns实现一种链式插件结构,将DNS的逻辑抽象成一个个插件,能够灵活的使用。
常用的插件如下:

插件名称

功能描述

loadbalance

提供基于DNS的负载均衡

loop

检测在DNS解析过程中出现的简单循环问题

cache

提供前端缓存功能

health

对Endpoint进行健康检查

kubernetes

从kubernetes中读取zone数据

etcd

从etcd读取zone数据,可用于自定义域名

file

从RFC1035格式文件中读取zone数据

hosts

使用/etc/hosts文件或者其他文件读取zone数据,可以用户自定义域名

auto

从磁盘中自动加载区域文件

reload

定时自动重新加载Corefile配置文件的内容

forward

转发域名查询到上游DNS服务器

proxy

转发特定的域名查询到其他DNS服务器,同时提供多个DNS服务器的负载均衡功能

prometheus

为prometheus系统提供采集性能指标的url

pprof

在url路径/debug/pprof下提供运行时的性能数据

log

对dns查询进行日志记录

errors

对错误信息进行日志记录

在上述事例中域名"cluster.local"的域名设置了一系列插件,域名解析时这些插件将从上往下依次执行:

.:53 {
        errors
        health
        ready
        kubernetes cluster.local in-addr.arpa ip6.arpa {  # 指定域名,可指定多个,要包含kubelet中配置的clusterDomain
            pods insecure
            fallthrough in-addr.arpa ip6.arpa
            ttl 30
        }
        prometheus :9153
        forward . /etc/resolv.conf
        cache 30
        loop
        reload
        loadbalance
    }

另外,etcd和hosts插件都可以用于用户自定义域名记录
下面是使用etcd插件的配置示例,将已.com结尾的域名配置为从etcd中获取,并将域名记录保存在/skydns路径下:

{
  etcd com {
    path /skydns
    endpoint http://10.0.1.111:2379
    upstream /etc/resolve.conf
  }

  cache 160 com
  loadbalance
  proxy . /etc/resolve.conf
}

如果用户在etcd中插入一条dns记录,客户端应用应该就可以解析这个域名了:
etcdctl put /skydns/com/test '{"host": "10.1.1.1", "ttl": 60}' 客户端解析域名:
nslookup test.com forward和proxy插件都可以用于配置上游DNS服务器或其他DNS服务器,当coredns中查询不到域名时,会到其他DNS服务器去查询。

coredns域名解析的格式

service的ip:
<svc name>.<namespace>.svc.cluster.local # cluster.local为上面定义的域名
statefulset内的pod域名解析
<pod名>.<headless service名>.<namespace>.svc.cluster.local # 有状态的应用的pod可以进行域名解析,无状态应用不可以,域名解析需要配置一个headless service

pod级别的DNS配置

除了使用集群范围的DNS服务(coredns),pod内也可以直接设置dns的相关策略和配置。主要由两个参数来设置:spec.dnsPolicyspec.dnsConfig 示例:

dnsPolicy: None # 清除dns规则,Default:与宿主机一致,ClusterFirst:使用coredns的,如设置了 hostNetwork = true 时,ClusterFirst 会被强制转化为 Default
      dnsConfig: # 额外配置host文件dns
        nameservers:
          - 172.32.1.201
        searches:
          - ns1.svc.cluster.local
		options:
		  - name: ndots
		    value: "2"
		  - name: edns0

部署pod后,可从pod的/etc/resolve.conf查看配置的域名

dnsPolicy配置

参数

说明

Default

继承pod所在宿主机的DNS配置

ClusterFirst

优先使用k8s环境的dns服务(coredns),无法解析的域名转发到从宿主机继承的DNS服务器,如设置了 hostNetwork = true 时,ClusterFirst 会被强制转化为 Default

ClusterFirstWithHostNet

与ClusterFirst相同,对使用hostNetwork模式运行的pod,应明确指定改策略

None

清除dns规则,通过dnsConfig配置

dnsConfig配置

参数

说明

nameservers

一组DNS服务器的列表,最多可以设置3个

searches

一组用户域名搜索的DNS域名后缀,最多可以设置6个

options

配置其他可选DNS参数,例如ndots、timeout等,以name或name/value对的形式表示