KEDA 是一个基于 Kubernetes 的事件驱动自动缩放器。使用 KEDA,您可以根据需要处理的事件数量来驱动 Kubernetes 中任何容器的扩展。KEDA可以支持很多自定义事件源,如:Mysql、MongoDB、Redis、ActiveMQ、Kafka、Prometheus、Metrics API等。本文使用nginx中的stub_status数据 + Prometheus为事件源进行KEDA HPA配置。
一、开启nginx(stub_status)
nginx中的stub_status模块主要用于查看Nginx的一些状态信息。
1)查看nginx时候有安装该模块。
1
| /usr/local/nginx/sbin/nginx -V
|
2)安装stub_status模块
(注意:有的话可以忽略此步骤,就不用安装了)
在nginx编译安装的时候加上参数 “–with-http_stub_status_module”,就安装了这个模块。
1
| ./configure --with-http_stub_status_module
|
3)开启stub_status
1 2 3 4 5
| location /nginx_status { stub_status on; allow 127.0.0.1; deny all; }
|
二、在kubernetes中运行nginx-prometheus-exporter
nginx-prometheus-exporter 是将 stub_status 指标转换为 Prometheus 指标类型,最终可以由 Prometheus 进行收集。
在Kubernetes里运行
1)创建一个无状态服务(Deployment)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| apiVersion: apps/v1 kind: Deployment metadata: name: nginx-prometheus labels: workload.user.cattle.io/workloadselector: apps.deployment-default-nginx-prometheus namespace: default spec: selector: matchLabels: workload.user.cattle.io/workloadselector: apps.deployment-default-nginx-prometheus template: metadata: labels: workload.user.cattle.io/workloadselector: apps.deployment-default-nginx-prometheus spec: containers: - imagePullPolicy: Always name: nginx-prometheus image: nginx/nginx-prometheus-exporter:0.10.0 command: - nginx-prometheus-exporter args: - '-nginx.scrape-uri=http://127.0.0.1/nginx_status' restartPolicy: Always
|
2)创建一个Service服务
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| apiVersion: v1 kind: Service metadata: name: nginx-prometheus labels: metrics-prometheus-discovery: 'true' namespace: default spec: ports: - name: prometheus port: 9113 protocol: TCP targetPort: 9113 type: ClusterIP
|
三、配置kubernetes中的Monitor服务
1)创建一个ServiceMonitor
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| apiVersion: monitoring.coreos.com/v1 kind: ServiceMonitor metadata: name: nginx-monitor namespace: default spec: selector: matchLabels: metrics-prometheus-discovery: 'true' namespaceSelector: matchNames: - default endpoints: - port: prometheus interval: 5s
|
2)创建KEDA(ScaledObject)缩放规则
Prometheus的集群内访问地址是:http://prometheus-operated.cattle-prometheus.svc:9090
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| apiVersion: keda.sh/v1alpha1 kind: ScaledObject metadata: name: nginx-prometheus-scaledobject namespace: default spec: scaleTargetRef: name: nginx pollingInterval: 5 cooldownPeriod: 60 minReplicaCount: 1 maxReplicaCount: 3 triggers: - type: prometheus metadata: serverAddress: http://prometheus-operated.cattle-monitoring-system.svc.cluster.local:9090 metricName: nginx_http_requests_total threshold: '100' query: sum(rate(nginx_http_requests_total[10s]))
|
ps:
在Docker中运行
1
| docker run -p 9113:9113 nginx/nginx-prometheus-exporter:0.10.0 -nginx.scrape-uri=http://127.0.0.1/nginx_status
|
运行后,可以通过9113 端口来访问 Prometheus 收集的数据,可以配合Grafana来实现数据可视化。
1
| curl http://localhost:9113/metrics
|