net.LookupSRV()查询k8s无头服务

(金庆的专栏 2021.2)

如下创建 StatefulSet 和 Headless Service: test.yaml

apiVersion: v1
kind: Service
metadata:
  name: headless-svc
  labels:
    app: headless-svc
spec:
  ports:
  - port: 80
    name: aaaa
  - port: 20080
    name: bbbb
  selector:
    app: headless-pod
  clusterIP: None
  
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: statefulset-test
spec:
  serviceName: headless-svc
  replicas: 3
  selector:
    matchLabels:
      app: headless-pod
  template:
    metadata:
      labels:
        app: headless-pod
    spec:
      containers:
      - name: myhttpd
        image: httpd
        ports:
        - containerPort: 80
        - containerPort: 20080

部署:

kubectl apply -f test.yaml

然后开一个 shell:

kubectl run mygolang -it --image golang -- bash
If you don't see a command prompt, try pressing enter.
root@mygolang:/go#

先装个 vim:

apt install vim

然后写个 golang 测试程序,向 DNS 查询 bbbb 服务的地址与端口:

root@mygolang:/jinqing# cat main.go
package main

import (
    "fmt"
    "github.com/davecgh/go-spew/spew"
    "net"
)

func main() {
    cname, addresses, err := net.LookupSRV("bbbb", "tcp", "headless-svc.default.svc.cluster.local")
    if err != nil {
        fmt.Printf("failed: %s\n", err)
    }
    fmt.Printf("cname: %s\n", cname)
    spew.Dump(addresses)
}
root@mygolang:/jinqing#

运行结果为:

cname: _bbbb._tcp.headless-svc.default.svc.cluster.local.
([]*net.SRV) (len=3 cap=4) {
 (*net.SRV)(0xc00000e220)({
  Target: (string) (len=58) "statefulset-test-0.headless-svc.default.svc.cluster.local.",
  Port: (uint16) 20080,
  Priority: (uint16) 0,
  Weight: (uint16) 33
 }),
 (*net.SRV)(0xc00000e1e0)({
  Target: (string) (len=58) "statefulset-test-2.headless-svc.default.svc.cluster.local.",
  Port: (uint16) 20080,
  Priority: (uint16) 0,
  Weight: (uint16) 33
 }),
 (*net.SRV)(0xc00000e200)({
  Target: (string) (len=58) "statefulset-test-1.headless-svc.default.svc.cluster.local.",
  Port: (uint16) 20080,
  Priority: (uint16) 0,
  Weight: (uint16) 33
 })
}

多次运行发现结果项次序固定,并没有按权重随机。

Service yaml 定义中,必须为每个端口命名,不然没法查询。

    cname, addresses, err := net.LookupSRV("bbbb", "tcp", "headless-svc.default.svc.cluster.local")

可利用默认域名后缀简写为

    cname, addresses, err := net.LookupSRV("bbbb", "tcp", "headless-svc")

输出相同。

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐