问题

在使用nslookup测试 Pod 的 DNS 记录发现 Pod 的域名没有按照<pod name>.<svc name>.<namespace>.svc.cluster.local的格式来生成,而是<pod name>变成了<IP Address>的形式做 DNS 解析域名。解析示例如下:

# kubectl exec -t busybox -- nslookup redis-headless.default.svc.cluster.local
Server:    172.16.0.10
Address 1: 172.16.0.10 kube-dns.kube-system.svc.cluster.local

Name:      redis-headless.default.svc.cluster.local
Address 1: 10.104.157.115 10-104-157-115.redis-headless.default.svc.cluster.local
Address 2: 10.104.157.108 10-104-157-108.redis-headless.default.svc.cluster.local

解决:

Statefulset 的 spec中没有指定serviceName。在kubectl explain statefulset.spec.serviceName中的解释是: serviceName is the name of the service that governs this StatefulSet. This service must exist before the StatefulSet, and is responsible for the network identity of the set. Pods get DNS/hostnames that follow the pattern: pod-specific-string.serviceName.default.svc.cluster.local where"pod-specific-string" is managed by the StatefulSet controller.

翻译过来就是:

serviceName是管理此StatefulSet的服务的名称。此服务必须在StatefulSet之前存在,并负责该集的网络标识。pod获取遵循以下模式的DNS/主机名:pod-specific-string.serviceName.default.svc.cluster.local,其中“特定于pod的字符串”由StatefulSet控制器管理。

经过重新设定serviceName后,示例如下:

apiVersion: apps/v1
kind: StatefulSet
m
etadata:
  name: redis
spec:
  replicas: 2
  serviceName: redis-headless
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      containers:
      - name: redis
        image: redis:7.0
        ports:
        - containerPort: 6379
          name: redis

---

apiVersion: v1
kind: Service
metadata:
  name: redis-headless
  labels:
    service: redis
spec:
  selector:
    app: redis
  type: ClusterIP
  clusterIP: None
  ports:
  - port: 6379
    protocol: TCP
    targetPort: 6379

查询的 DNS 域名如下所示:

# kubectl exec -t busybox -- nslookup redis-headless.default.svc.cluster.local
Server:    172.16.0.10
Address 1: 172.16.0.10 kube-dns.kube-system.svc.cluster.local

Name:      redis-headless.default.svc.cluster.local
Address 1: 10.104.157.117 redis-1.redis-headless.default.svc.cluster.local
Address 2: 10.104.157.116 redis-0.redis-headless.default.svc.cluster.local