Skip to content

08 — Service / Ingress / Gateway API 深度教材

服务发现与流量入口是 K8s 网络的核心。本章覆盖 kube-proxy 三模式、Ingress Controller 原理、Gateway API 迁移路径。


1. Service 类型与原理

1.1 四种 Service 类型

类型访问方式场景
ClusterIP集群内部微服务间通信(默认)
NodePort节点IP:端口外部访问(开发/小规模)
LoadBalancer云 LB外部访问(生产)
ExternalNameCNAME 记录映射外部服务
bash
# Headless Service(ClusterIP: None)
# 用途:StatefulSet、自定义服务发现
# DNS 直接返回 Pod IP 列表而非 ClusterIP

1.2 kube-proxy 三模式对比

┌──────────────┬───────────────┬─────────────┬──────────────┐
│ 特性          │ userspace      │ iptables     │ IPVS         │
├──────────────┼───────────────┼─────────────┼──────────────┤
│ 性能          │ 最差           │ 中等         │ 最好          │
│ 查找复杂度     │ N/A            │ O(n)         │ O(1)         │
│ 适用规模       │ <100 svc       │ <1000 svc    │ >1000 svc    │
│ 调度算法       │ 轮询           │ 随机         │ 多种(rr/wrr)│
│ 连接保持       │ 不支持         │ 不支持       │ sh 算法支持  │
│ 状态          │ 已废弃         │ 默认         │ 推荐大规模    │
└──────────────┴───────────────┴─────────────┴──────────────┘
bash
# 查看 kube-proxy 模式
kubectl get cm kube-proxy -n kube-system -o yaml | grep mode

# IPVS 规则查看
ipvsadm -Ln | head -30
ipvsadm -Ln --stats

# iptables 规则查看
iptables -t nat -L KUBE-SERVICES -n --line-numbers | head -20

2. Ingress Controller

2.1 工作原理

用户请求 → DNS → 云 LB(NodePort/LB 模式)→ Ingress Controller Pod
  → 根据 Host/Path 匹配规则 → 转发到后端 Service → Pod

Ingress Controller 本质是一个反向代理:
  - Nginx Ingress:基于 Nginx
  - Traefik:自带 UI,自动发现
  - Kong:API 网关功能丰富
  - Cilium Gateway:eBPF 高性能

2.2 Nginx Ingress 生产配置

yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: web-ingress
  annotations:
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-body-size: "100m"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "120"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "120"
    nginx.ingress.kubernetes.io/rate-limit: "100"
    nginx.ingress.kubernetes.io/rate-limit-window: "1m"
spec:
  ingressClassName: nginx
  tls:
  - hosts:
    - app.example.com
    secretName: app-tls
  rules:
  - host: app.example.com
    http:
      paths:
      - path: /api
        pathType: Prefix
        backend:
          service:
            name: api-service
            port:
              number: 8080
      - path: /
        pathType: Prefix
        backend:
          service:
            name: web-service
            port:
              number: 80

2.3 Ingress Controller 排障

bash
# 1. 确认 Ingress 资源已创建
kubectl get ingress

# 2. 确认 Ingress Controller Pod 运行正常
kubectl get pods -n ingress-nginx

# 3. 检查 Nginx 配置(Ingress Controller 内部)
kubectl exec -n ingress-nginx <controller-pod> -- cat /etc/nginx/nginx.conf | grep -A10 'server_name.*app.example'

# 4. 检查后端 Service 和 Endpoints
kubectl get endpoints <backend-service>

# 5. 查看 Ingress Controller 日志
kubectl logs -n ingress-nginx <controller-pod> --tail=50

# 6. 常见问题
# - 502 Bad Gateway: 后端 Pod 未就绪或端口不匹配
# - 504 Gateway Timeout: 后端响应太慢
# - 404 Not Found: Ingress 规则未匹配

3. Gateway API(Ingress 的演进)

yaml
# Gateway API 三大资源
# 1. GatewayClass:定义控制器(类似 IngressClass)
# 2. Gateway:定义入口(监听器、地址)
# 3. HTTPRoute:定义路由规则

apiVersion: gateway.networking.k8s.io/v1
kind: Gateway
metadata:
  name: web-gateway
spec:
  gatewayClassName: nginx
  listeners:
  - name: https
    protocol: HTTPS
    port: 443
    tls:
      mode: Terminate
      certificateRefs:
      - name: app-tls
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: web-route
spec:
  parentRefs:
  - name: web-gateway
  hostnames:
  - app.example.com
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: /api
    backendRefs:
    - name: api-service
      port: 8080
      weight: 90        # 灰度发布:90% 流量
    - name: api-service-v2
      port: 8080
      weight: 10        # 10% 流量到 v2

Gateway API vs Ingress 对比

特性IngressGateway API
路由能力基础 Host/PathHeader/Method/Query/权重
角色分离单一资源GatewayClass/Gateway/Route
TLS 管理注解方式原生 TLS 配置
灰度发布注解 hack原生权重路由
TCP/UDP 支持注解方式原生 TCPRoute/UDPRoute

4. 面试高频问题

Q: Service 如何实现负载均衡?

1. ClusterIP Service 通过 kube-proxy 创建 DNAT 规则
2. iptables 模式:随机选择后端 Pod(概率均等)
3. IPVS 模式:支持 rr/wrr/lc/sh 等算法
4. SessionAffinity: ClientIP 可实现会话保持
5. ExternalTrafficPolicy: Local 保留客户端源 IP

Q: Ingress 与 LoadBalancer Service 的区别?

LoadBalancer Service:
  - 四层负载均衡(TCP/UDP)
  - 一个 Service 一个 LB IP
  - 成本:每个 Service 需要一个云 LB

Ingress:
  - 七层负载均衡(HTTP/HTTPS)
  - 多个 Service 共享一个 LB IP
  - 支持域名/路径路由、TLS 终止
  - 成本:所有 HTTP 服务共享一个 LB