在 Kubernetes 中使用 Nginx Ingress Controller,可以实现速率限制的功能,以限制对后端服务的请求速率。速率限制是为了防止过多的请求压力导致后端服务过载,保护服务的稳定性。
下面针对该场景进行演示说明:
1.在192.168.1.31 主机上修改/etc/hosts文件,添加nginx.test.com和192.168.1.35的映射关系
[root@k8s-master01 ~]# vim /etc/hosts
192.168.1.35 k8s-node02 nginx.test.com
2.在没有设置加速率限制的条件下,使用 ab 进行访问,使用 10 个并发连接(并发用户)发送 100 个请求到 https://nginx.test.com/ 进行性能测试,观察到失败请求数为 0
[root@k8s-master01 ~]# ab -c 10 -n 100 https://nginx.test.com/ | grep requests
Complete requests: 100
Failed requests: 0
Time per request: 0.532 [ms] (mean, across all concurrent requests)
Percentage of the requests served within a certain time (ms)
上面参数说明:
-c 10: 表示使用 10 个并发连接,也就是同时有 10 个用户发送请求-n 100: 表示总共发送 100 个请求https://nginx.test.com/: 这是要进行性能测试的目标 URL,其中https表示使用 HTTPS 协议
3.添加速率限制,限制只能有一个连接,只需要添加 nginx.ingress.kubernetes.io/limit-connections 为 1 即可
[root@k8s-master01 ~]# vim auth-rate-limit.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
annotations:
kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/limit-connections: "1"
name: nginx-ingress
namespace: study-ingress
spec:
ingressClassName: nginx # for k8s >= 1.22+
rules:
- host: nginx.test.com
http:
paths:
- backend:
service:
name: nginx
port:
number: 80
path: /
pathType: ImplementationSpecific
上面参数说明:
nginx.ingress.kubernetes.io/limit-connections注解设置了连接数限制为 1,意味着每个客户端 IP 地址最多只能同时保持一个连接到后端服务。如果同一客户端的第二个连接请求到达,Nginx Ingress Controller 将会将其排队等待,直到之前的连接关闭。
更新Ingress
[root@k8s-master01 ~]# kubectl replace -f auth-rate-limit.yaml
4.再次使用 ab 测试,观察到失败请求数为 62
[root@k8s-master01 ~]# ab -c 10 -n 100 https://nginx.test.com/ | grep requests
Complete requests: 100
Failed requests: 62
Time per request: 0.577 [ms] (mean, across all concurrent requests)
Percentage of the requests served within a certain time (ms)