通过 kubedns 访问 Pod 而不暴露为服务

Accessing Pod through kubedns without expose as service

我正在尝试在不公开为服务的情况下测试 pod 间通信。 我读到 pod 在 kubedns 中确实有 FQDN。 kubernetes doc

默认应该是(A记录)
metadata_name.namespace.svc.cluster.local

hostname.subdomain.namespace.svc.cluster.local

但我尝试了 curl 和 nslookup。都失败了。服务很健康,我可以用 pod IP (172.17.0.5)

curl

curl: (6) could not resolve host
nslookup: can't resolve '(null)': Name does not resolved

我错过了什么?

If there exists a headless service in the same namespace as the pod and with the same name as the subdomain, the cluster’s KubeDNS Server also returns an A record for the Pod’s fully qualified hostname. For example, given a Pod with the hostname set to “busybox-1” and the subdomain set to “default-subdomain”, and a headless Service named “default-subdomain” in the same namespace, the pod will see its own FQDN as “busybox-1.default-subdomain.my-namespace.svc.cluster.local”.

因此,在您的情况下,您需要为 pod 定义子域并使用指向 pods.

的相同名称创建 headless service

我建议为此添加类型为 ClusterIP 的服务:https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services-service-types

kind: Service
apiVersion: v1
metadata:
  name: my-service
spec:
  selector:
    app: MyApp
  ports:
  - protocol: TCP
    port: 80
    targetPort: 80
  type: ClusterIP

它不会将您的 pod 暴露在集群之外。请注意,这是默认服务类型,您可以省略指定它。

然后像这样查询服务:

curl http://my-service.namespace.svc.cluster.local

这种方法比直接使用 pod DNS 更好,原因有两个:

  • 您不需要知道确切的广告连播名称(例如 name-id

  • 在这种情况下,您可以 运行 多个 pods 服务后面,它会 load-balance 请求。或者只是 运行 一个,它完全符合您的要求。