且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过查询DNS srv记录获取kubernetes pod的IP地址?

更新时间:2023-10-31 11:20:58

您可以使用无头服务(因此,没有ClusterIP,也没有内部负载平衡).如果提供选择器,则可以查询服务的A记录.

You can use a headless service (therefore no ClusterIP and no internal loadbalancing). If you provide a selector, you can query for A records of the service.

请参阅: https://kubernetes.io/docs/概念/服务网络/服务/#headless-服务

请考虑以下示例:

部署一些吊舱:

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.16
        ports:
        - containerPort: 80

为此部署添加了以下无头服务:

For this deployment the following headless service is added:

apiVersion: v1
kind: Service
metadata:
  name: nginx
  labels:
    app: nginx
spec:
  ports:
  - port: 80
    name: web
  clusterIP: None
  selector:
    app: nginx

现在可以使用DNS(在群集内部)进行查询

This can now be queried using DNS (inside the cluster)

$ kubectl run shell  -i --rm --tty --restart=Never --image=busybox
# nslookup -type=A nginx
Server:     10.96.0.10
Address:    10.96.0.10:53

Name:   nginx.default.svc.cluster.local
Address: 10.34.0.2
Name:   nginx.default.svc.cluster.local
Address: 10.42.0.2
Name:   nginx.default.svc.cluster.local
Address: 10.46.0.1

所有内部Pod IP均作为DNS A记录返回.

All internal Pod IPs are returned as DNS A records.