CoreDNS is Rancher’s default DNS component and you want it to return hosts static file results instead of querying upstream DNS servers.

This solves the problem of upstream DNS servers not being able to resolve the queried domain name at all.

Configuring hosts ConfigMap

Under the kube-system namespace, create a new ConfigMap coredns-hosts.

1
2
3
4
5
6
7
8
9
apiVersion: v1
kind: ConfigMap
metadata:
  name: coredns-hosts
  namespace: kube-system
data:
  coredns-hosts: |-
    127.0.0.1 baidu.com
    127.0.0.2 www.baidu.com      

Modify the contents of coredns-hosts as appropriate.

Modify the coredns deployment

Modify Deployment coredns under the kube-system namespace, mount ConfigMap coredns-hosts to /etc/hosts-custom/coredns-hosts in the Pod, and note the volumeMounts and volumes sections below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    ...
  labels:
    k8s-app: kube-dns
    kubernetes.io/name: CoreDNS
  name: coredns
  namespace: kube-system
  ...
spec:
  ...
  template:
    metadata:
      ...
    spec:
      ...
      containers:
      - ...
        image: rancher/mirrored-coredns-coredns:1.8.0
        ...
        volumeMounts:
        ...
        - mountPath: /etc/hosts-custom
          name: coredns-hosts
      
      volumes:
      ...
      - configMap:
          defaultMode: 420
          name: coredns-hosts
          optional: false
        name: coredns-hosts

Modify CoreDNS configuration

Modify ConfigMap coredns under kube-system namespace, Key Corefile is its configuration file, add the following 3 lines.

1
2
3
4
5
6
7
{
    ...
    hosts /etc/hosts-custom/coredns-hosts <zone1> <zone2> ... {
      fallthrough <zone1> <zone2> ...
    }
    ...
}

The above <zone> means the domain name suffix, e.g. edu.cn then all queries for domains with the suffix .edu.cn will go to /etc/hosts-custom/coredns-hosts for answers.

fallthrough is used to set which <zone>s can be submitted to the upstream DNS server if the answer is not found.

Loading configuration

CoreDNS will load the configuration automatically (without rebooting), and it will also load it automatically if you change the hosts file.

Then just go to any Pod and experiment with nslookup.

Ref