跳转至

Service、DNS 与入口控制器

Pod 会重建、IP 会变化。Service 通过 Label Selector 选择一组 Ready Pod,并由 EndpointSlice 记录实际后端;CoreDNS 为 Service 提供稳定名称。外部 HTTP/HTTPS 流量再通过 Ingress Controller 或 Gateway Controller 进入 Service。

集群内客户端 → Service DNS → ClusterIP → EndpointSlice → Ready Pod
外部客户端 → LB/入口地址 → Ingress/Gateway Controller → Service → Pod

Service

apiVersion: v1
kind: Service
metadata:
  name: web
spec:
  selector:
    app: web
  ports:
    - port: 80
      targetPort: 80
  type: ClusterIP
kubectl get svc,endpointslice
kubectl describe svc web
类型 用途
ClusterIP 集群内访问,默认类型。
NodePort 通过节点端口暴露服务。
LoadBalancer 由云/基础设施实现提供外部负载均衡。

Service Selector 与 Pod Label 不匹配、Pod Readiness 失败或端口 targetPort 错误,都会造成没有可用后端。

kubectl get pods -l app=web --show-labels
kubectl get endpointslice -l kubernetes.io/service-name=web -o wide
kubectl describe service web

CoreDNS 与服务发现

同 Namespace 可使用 web,跨 Namespace 使用:

web.app.svc.cluster.local
kubectl get pods -n kube-system -l k8s-app=kube-dns
kubectl get service -n kube-system kube-dns
kubectl run dns-test --rm -it --restart=Never --image=busybox:1.36 -- nslookup web.app.svc.cluster.local

DNS 失败时先区分 CoreDNS 服务不可用、Pod 到 DNS ClusterIP 不通、上游 DNS 失败、搜索域/ndots 行为或 NetworkPolicy 拦截 53/UDP/TCP。

Ingress 与 Ingress Controller

Ingress 是 HTTP/HTTPS 路由规则;Ingress Controller 才是读取规则并真正配置代理/负载均衡的数据面。只创建 Ingress YAML,没有安装兼容 Controller,不会产生入口能力。

常见 Controller 实现包括 ingress-nginx、Traefik,以及云厂商/负载均衡产品提供的实现。选择时关注维护状态、Kubernetes 版本、TLS、真实客户端 IP、性能、监控和企业网络集成,不要把不同 Controller 的 Annotation 混用。

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web
  namespace: app
spec:
  ingressClassName: nginx
  rules:
    - host: web.example.com
      http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: web
                port:
                  number: 80
kubectl get ingressclass
kubectl get ingress -A
kubectl describe ingress web -n app
kubectl get pods,svc -n ingress-nginx

排障时沿着域名 DNS → 外部 LB/IP → Controller Service/Pod → Ingress 规则 → 后端 Service → EndpointSlice → Pod 逐层检查。

Gateway API

Gateway API 将基础设施入口与业务路由分离:GatewayClass 表示 Controller 类型,Gateway 表示入口实例,HTTPRoute/TCPRoute 等表示路由。它更适合多团队、跨 Namespace 授权和复杂流量治理。

Gateway API 同样需要已经安装实现它的 Controller;创建 Gateway/HTTPRoute 不会凭空产生负载均衡器。新平台可优先评估 Gateway API,已有稳定 Ingress 不必为了概念更新立即迁移。

TLS

TLS Secret 与 Ingress/Gateway 引用必须位于实现允许的范围内。证书续期、私钥权限、SNI、完整证书链和 Controller Reload 都要监控。不要把证书私钥明文提交 Git。

常见故障

现象 优先检查
Service 无 Endpoint Selector、Pod Label、Readiness、EndpointSlice
ClusterIP 不通 CNI、kube-proxy/eBPF 数据面、端口映射、NetworkPolicy
域名解析失败 CoreDNS Pod/Service、53 端口、上游 DNS、Pod resolv.conf
Ingress 没有地址 IngressClass、Controller、外部 LB/MetalLB/云集成
入口 404 Host/Path 是否匹配,是否命中默认后端或错误 Controller
入口 502/503 后端 Service/Endpoint/端口、Readiness、协议是否一致
HTTPS 证书错误 DNS、SNI、Secret、证书链、到期时间和 Controller 日志

官方参考:ServiceIngressGateway API