将请求代理到加权后端
加权路由通过按指定权重在多个上游服务之间分发流量来实现负载均衡。你可以让部分后端接收更多流量、其他后端接收较少流量,从而优化资源使用并提升服务可靠性。
本指南介绍如何使用 Ingress Controller 配置加权路由。
前提条件
启动示例上游服务
创建 Kubernetes manifest 文件,定义两个示例上游服务 echo-1 和 echo-2:
lb-two-http-echo.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: echo-1
namespace: aic
spec:
replicas: 1
selector:
matchLabels:
app: echo-1
template:
metadata:
labels:
app: echo-1
spec:
containers:
- name: http-echo
image: hashicorp/http-echo:0.2.3
args:
- "-text=Hello from pod $(POD_NAME) in upstream 1"
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
ports:
- containerPort: 5678
---
apiVersion: v1
kind: Service
metadata:
name: echo-1
namespace: aic
spec:
selector:
app: echo-1
ports:
- protocol: TCP
port: 80
targetPort: 5678
type: ClusterIP
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: echo-2
namespace: aic
spec:
replicas: 1
selector:
matchLabels:
app: echo-2
template:
metadata:
labels:
app: echo-2
spec:
containers:
- name: http-echo
image: hashicorp/http-echo:0.2.3
args:
- "-text=Hello from pod $(POD_NAME) in upstream 2"
env:
- name: POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
ports:
- containerPort: 5678
---
apiVersion: v1
kind: Service
metadata:
name: echo-2
namespace: aic
spec:
selector:
app: echo-2
ports:
- protocol: TCP
port: 80
targetPort: 5678
type: ClusterIP
当请求 / 时,每个服务都会返回自身 Pod 名称和上游编号,便于识别 。
将配置应用到集群:
kubectl apply -f lb-two-http-echo.yaml
创建路由
创建 Kubernetes manifest,按指定权重在两个上游服务之间对请求进行负载均衡:
- Gateway API
- APISIX CRD
lb-route.yaml
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
namespace: aic
name: lb-route
spec:
parentRefs:
- name: apisix
rules:
- matches:
- path:
type: Exact
value: /
backendRefs:
- name: echo-1
port: 80
weight: 1
- name: echo-2
port: 80
weight: 4
lb-route.yaml
apiVersion: apisix.apache.org/v2
kind: ApisixRoute
metadata:
namespace: aic
name: lb-route
spec:
ingressClassName: apisix
http:
- name: lb-route
match:
paths:
- /
backends:
- serviceName: echo-1
servicePort: 80
weight: 1
- serviceName: echo-2
servicePort: 80
weight: 4
将配置应用到集群:
kubectl apply -f lb-route.yaml
验证
将网关 Service 端口暴露到本地机器:
# 替换为你的网关 Service 名称
kubectl port-forward svc/<gateway-service-name> 9080:80 &
连续向路由发送 50 次请求,观察负载均衡效果:
resp=$(seq 50 | xargs -I{} curl "http://127.0.0.1:9080/" -sL) && \
count_echo1=$(echo "$resp" | grep "upstream 1" | wc -l) && \
count_echo2=$(echo "$resp" | grep "upstream 2" | wc -l) && \
echo "echo-1: $count_echo1, echo-2: $count_echo2"
该命令会统计两个服务各自处理的请求数量,例如:
echo-1: 9, echo-2: 41
请求在两个服务之间的分布应接近 1:4,但不一定完全精确。轻微偏差是因为网关以多个 worker 运行。