You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Kubernetes Service负载均衡两个Deployment的Pod?

解决方案

1. 调整两个Deployment的容器端口配置

给两个Deployment的容器端口设置相同的端口名称,实际端口分别对应80(API副本)和8800(Kinesis副本),同时确保所有Pod带有共同标签,供Service统一选择:

API Deployment(3副本)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: your-api
      role: http-server
  template:
    metadata:
      labels:
        app: your-api
        role: http-server
    spec:
      containers:
      - name: api-container
        image: your-aspnet-image
        ports:
        - name: http  # 统一端口名称
          containerPort: 80
        env:
        - name: KINESIS_ENABLED
          value: "false"  # 禁用Kinesis消费者逻辑

Kinesis Consumer Deployment(1副本)

apiVersion: apps/v1
kind: Deployment
metadata:
  name: kinesis-deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: your-api
      role: kinesis-consumer
  template:
    metadata:
      labels:
        app: your-api
        role: kinesis-consumer
    spec:
      containers:
      - name: api-container
        image: your-aspnet-image
        ports:
        - name: http  # 与API副本使用相同的端口名称
          containerPort: 8800
        env:
        - name: KINESIS_ENABLED
          value: "true"  # 启用Kinesis消费者逻辑

2. 创建统一Service实现负载均衡

配置Service选择所有带有app: your-api标签的Pod,使用端口名称作为目标端口(而非固定数字),Kubernetes会自动匹配每个Pod对应的实际容器端口:

apiVersion: v1
kind: Service
metadata:
  name: your-api-service
spec:
  type: ClusterIP  # 可根据需求替换为NodePort/LoadBalancer
  selector:
    app: your-api  # 匹配两个Deployment下的所有Pod
  ports:
  - name: http
    port: 80  # Service对外暴露的端口
    targetPort: http  # 匹配Pod中定义的端口名称
    protocol: TCP

3. 验证配置

  • 执行kubectl get pods --show-labels,确认所有4个Pod都带有app: your-api标签
  • 执行kubectl describe service your-api-service,查看Endpoints列表,应包含4个Pod的IP及对应端口
  • 发送测试HTTP请求,验证流量会均匀分发到所有Pod

端口重复错误原因说明

之前的问题通常是因为直接用数字端口作为targetPort(比如Service指定targetPort:80,但Kinesis Pod的容器端口是8800,导致端口不匹配),或配置Service端口时重复使用了相同名称。通过统一端口名称、用名称而非数字匹配目标端口,即可避免此类冲突。

内容的提问来源于stack exchange,提问作者AceGambit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:40:36