Home

Kubernetes 中 Service 和 Ingress 的深度解析

以下是对 Kubernetes 中 ServiceIngress 的深度解析,包含功能对比、协同关系、工作原理及实践指南:


一、核心功能定位对比

Service:L4 层流量管家

|请求| S[Service]
S -->|负载均衡| P1[Pod 1]
S -->|负载均衡| P2[Pod 2]
S -->|负载均衡| P3[Pod 3] -->

  • 核心作用
    • 为动态变化的 Pod 提供稳定访问端点(虚拟 IP + 端口)
    • 实现负载均衡(TCP/UDP 层)
    • 提供服务发现机制(通过 DNS)

Ingress:L7 层流量指挥官

graph LR
    Internet -->|HTTP/HTTPS| I[Ingress]
    I -->|基于路径路由| S1[Service A]
    I -->|基于域名路由| S2[Service B]
    I -->|TLS终止| S3[Service C]
  • 核心作用
    • 管理外部访问的 HTTP/HTTPS 路由规则
    • 实现域名和路径级别的流量分发
    • 集中处理 SSL/TLS 终止

二、详细功能解析

Service 的四种类型

类型访问范围典型场景示例配置片段
ClusterIP集群内部微服务间通信type: ClusterIP
NodePort节点外部可访问开发测试环境nodePort: 31000
LoadBalancer云服务商集成生产环境公网暴露type: LoadBalancer
Headless直接访问 Pod IP有状态服务(如数据库)clusterIP: None

Ingress 的核心能力

  1. 路由规则引擎
rules:
- host: shop.example.com
  http:
    paths:
    - path: /api
      backend:
        serviceName: api-service
        servicePort: 8080
    - path: /
      backend:
        serviceName: frontend-service
        servicePort: 80
  1. TLS 终止
tls:
- hosts:
  - "*.example.com"
  secretName: tls-wildcard-secret  # 存储证书的Secret
  1. 高级流量管理(通过注解):
metadata:
  annotations:
    nginx.ingress.kubernetes.io/canary: "true"
    nginx.ingress.kubernetes.io/canary-weight: "30%"

三、协同工作流程

sequenceDiagram
    participant C as Client
    participant L as LoadBalancer
    participant I as Ingress Controller
    participant S as Service
    participant P as Pod
    
    C->>L: HTTPS请求 shop.example.com/api
    L->>I: 转发到Ingress Controller
    I->>I: 1. 终止TLS(解密)
    I->>I: 2. 解析Host+Path
    I->>I: 3. 匹配路由规则
    I->>S: 4. 转发到 api-service:8080
    S->>P: 5. 负载均衡到后端Pod
    P->>I: 6. 返回响应数据
    I->>L: 7. 重新加密(如需)
    L->>C: 8. 返回HTTPS响应

关键协作点:

  1. Ingress 依赖 Service
    • Ingress 只定义路由规则,实际流量转发到 Service
  2. Service 屏蔽 Pod 变化
    • Pod 扩缩容时,Service 自动更新 Endpoints,Ingress 无需感知
  3. 层级关系
graph TD
    Internet --> Ingress
    Ingress --> Service
    Service --> Pod

四、架构实现细节

Ingress Controller 工作原理

graph TB
    IC[Ingress Controller] -->|监听| API[K8s API Server]
    API -->|通知变化| IC
    IC -->|生成配置| N[Nginx/Haproxy]
    N -->|重载| IC
    
    subgraph 数据面
        N -->|路由流量| S[Service]
        S --> P[Pod]
    end

流量处理流程(以 Nginx Ingress 为例):

  1. 配置同步
    • Controller 监听 Ingress 资源变更
    • 生成 Nginx 配置:/etc/nginx/nginx.conf
  2. 请求处理
server {
  listen 80;
  server_name shop.example.com;
  
  location /api {
    proxy_pass http://api-service.default.svc.cluster.local:8080;
  }
}
  1. 动态更新
nginx -s reload  # 不中断服务更新配置

五、最佳实践指南

1. Service 配置建议

apiVersion: v1
kind: Service
metadata:
  name: optimized-svc
spec:
  selector:
    app: frontend
  ports:
  - name: http
    port: 80          # Service 端口
    targetPort: 8080   # 容器端口
    protocol: TCP
  type: ClusterIP
  sessionAffinity: ClientIP  # 会话保持

2. Ingress 高级配置

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: production-ingress
  annotations:
    # 连接优化
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "15"
    # 限速防护
    nginx.ingress.kubernetes.io/limit-rpm: "1000"
    # 自动证书管理
    cert-manager.io/cluster-issuer: letsencrypt-prod
spec:
  tls:
  - hosts: [shop.example.com]
    secretName: tls-secret
  rules:
  - host: shop.example.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: frontend-svc
            port: 
              number: 80

3. 安全加固方案

annotations:
  # 启用WAF
  nginx.ingress.kubernetes.io/modsecurity: "on"
  # CORS控制
  nginx.ingress.kubernetes.io/enable-cors: "true"
  # 请求头控制
  nginx.ingress.kubernetes.io/proxy-add-original-uri-header: "true"

六、典型问题解决方案

场景1:灰度发布


metadata:
  annotations:
    nginx.ingress.kubernetes.io/canary: "true"
    nginx.ingress.kubernetes.io/canary-weight: "10%"

场景2:跨命名空间访问

rules:
- host: data.example.com
  http:
    paths:
    - path: /
      backend:
        service:
          name: database-service
          port: 5432
          namespace: db-prod  # 指定目标命名空间

场景3:TCP/UDP 服务暴露

# 需修改Controller配置
data:
  tcp-services: "9000: default/minecraft:25565"
  udp-services: "53: kube-system/kube-dns:53"

七、性能优化策略

  1. Ingress Controller 调优
# Nginx配置片段
worker-processes: auto
keepalive-requests: 10000
upstream-keepalive-connections: 200
  1. Service 拓扑感知
spec:
  topologyKeys: ["kubernetes.io/hostname"]
  1. 启用 eBPF 加速(Cilium 方案):
kube-proxy-replacement: strict

总结:核心差异对照表

特性ServiceIngress
工作层级L4 (传输层)L7 (应用层)
协议支持TCP/UDP/SCTPHTTP/HTTPS/GRPC/WebSocket
服务发现内置 DNS 解析依赖 Service 发现
外部访问能力需 NodePort/LoadBalancer直接暴露 HTTP 入口
路由能力基于域名/路径的复杂路由
SSL 处理不支持集中式 TLS 终止

黄金搭档模式
公网负载均衡器 → Ingress Controller → ClusterIP Service → Pod
此架构同时满足:

  • 外部可访问性(Ingress)
  • 内部稳定性(Service)
  • 灵活路由(Ingress 规则)
  • 安全控制(Ingress TLS)
Kubernetes 存储 AI