Kubernetes学习(七)补充:基于自定义指标进行扩缩容

资源指标只包含CPU、内存,一般来说也够了。但如果想根据自定义指标:如请求qps/5xx错误数来实现HPA,就需要使用自定义指标了,目前比较成熟的实现是 Prometheus Custom Metrics。自定义指标由Prometheus来提供,再利用k8s-prometheus-adpater聚合到apiserver,实现和核心指标(metric-server)同样的效果。

1、部署Prometheus

自行部署Prometheus,需要采集Pod指标

2、部署 Custom Metrics Adapter

prometheus采集到的metrics并不能直接给k8s用,因为两者数据格式不兼容,还需要另外一个组件(k8s-prometheus-adpater),将prometheus的metrics 数据格式转换成k8s API接口能识别的格式,转换以后,因为是自定义API,所以还需要用Kubernetes aggregator在主APIServer中注册,以便直接通过/apis/来访问。

GitHub - kubernetes-sigs/prometheus-adapter: An implementation of the custom.metrics.k8s.io API using PrometheusGitHub - kubernetes-sigs/prometheus-adapter: An implementation of the custom.metrics.k8s.io API using PrometheusGitHub - kubernetes-sigs/prometheus-adapter: An implementation of the custom.metrics.k8s.io API using Prometheus

该 PrometheusAdapter 有一个稳定的Helm Charts,我们直接使用。镜像可以替换成国内镜像。

验证适配器是否注册到APIServer:

[root@master chart]# kubectl get apiservices |grep custom 
v1beta1.custom.metrics.k8s.io          kube-system/prometheus-adapter   True        3m56s
[root@master chart]#

3、部署测试应用

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: metrics-app
  name: metrics-app
spec:
  replicas: 2
  selector:
    matchLabels:
      app: metrics-app
  template:
    metadata:
      labels:
        app: metrics-app
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "80"
        prometheus.io/path: "/metrics"
    spec:
      containers:
      - image: art.local:8081/docker-local/lizhenliang/metrics-app
        name: metrics-app
        ports:
        - name: web
          containerPort: 80
        resources:
          requests:
            cpu: 200m
            memory: 256Mi
        readinessProbe:
          httpGet:
            path: /
            port: 80
          initialDelaySeconds: 3
          periodSeconds: 5
        livenessProbe:
          httpGet:
            path: /
            port: 80
          initialDelaySeconds: 3
          periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: metrics-app
  labels:
    app: metrics-app
spec:
  type: NodePort
  ports:
  - name: web
    port: 80
    targetPort: 80
    nodePort: 30099
  selector:
    app: metrics-app

 该metrics-app暴露了一个Prometheus指标接口,提供2个指标:

http_requests_total
http_requests_per_second

4、创建自定义HPA策略

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: metrics-app-hpa-custom
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: metrics-app
  minReplicas: 1
  maxReplicas: 10
  metrics:
    - type: Pods
      pods:
        metric:
          name: http_requests_per_second
        target:
          type: AverageValue
          averageValue: 800m
[root@master k8s]# kubectl get hpa
NAME                     REFERENCE                TARGETS          MINPODS   MAXPODS   REPLICAS   AGE
metrics-app-hpa-custom   Deployment/metrics-app   <unknown>/800m   1         10        2          27s
[root@master k8s]#

此时适配器还不知道要什么指标(http_requests_per_second),HPA也就获取不到Pod提供指标。

5、配置适配器收集特定的指标

编辑PrometheusAdapter创建的prometheus-adapter Config Map:

新增查询规则

- seriesQuery: 'http_requests_total{kubernetes_namespace!="",kubernetes_pod_name!=""}'
      resources:
        overrides:
          kubernetes_namespace: {resource: "namespace"}
          kubernetes_pod_name: {resource: "pod"}
      name:
        matches: "^(.*)_total"
        as: "${1}_per_second"
      metricsQuery: 'sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)'

重新部署PrometheusAdapter后,再次查看hpa,此时能够获取到自定义指标

[root@master log]# kubectl get hpa
NAME                     REFERENCE                TARGETS     MINPODS   MAXPODS   REPLICAS   AGE
metrics-app-hpa-custom   Deployment/metrics-app   499m/800m   1         10        2          76m
[root@master log]#

6、压测,观察自定义指标扩缩容

[root@localhost ~]# ab -n 100000 -c 100 http://179.220.56.232:30099/metrics
[root@master ~]# kubectl get hpa
NAME                     REFERENCE                TARGETS        MINPODS   MAXPODS   REPLICAS   AGE
metrics-app-hpa-custom   Deployment/metrics-app   163846m/800m   1         10        10         5h46m
[root@master ~]# kubectl describe hpa metrics-app-hpa-custom 
Warning: autoscaling/v2beta2 HorizontalPodAutoscaler is deprecated in v1.23+, unavailable in v1.26+; use autoscaling/v2 HorizontalPodAutoscaler
Name:                                  metrics-app-hpa-custom
Namespace:                             default
Labels:                                <none>
Annotations:                           <none>
CreationTimestamp:                     Mon, 20 Mar 2023 10:01:59 +0800
Reference:                             Deployment/metrics-app
Metrics:                               ( current / target )
  "http_requests_per_second" on pods:  499m / 800m
Min replicas:                          1
Max replicas:                          10
Deployment pods:                       3 current / 3 desired
Conditions:
  Type            Status  Reason               Message
  ----            ------  ------               -------
  AbleToScale     True    ScaleDownStabilized  recent recommendations were higher than current one, applying the highest recent recommendation
  ScalingActive   True    ValidMetricFound     the HPA was able to successfully calculate a replica count from pods metric http_requests_per_second
  ScalingLimited  False   DesiredWithinRange   the desired count is within the acceptable range
Events:
  Type    Reason             Age   From                       Message
  ----    ------             ----  ----                       -------
  Normal  SuccessfulRescale  24m   horizontal-pod-autoscaler  New size: 4; reason: pods metric http_requests_per_second above target
  Normal  SuccessfulRescale  24m   horizontal-pod-autoscaler  New size: 8; reason: pods metric http_requests_per_second above target
  Normal  SuccessfulRescale  24m   horizontal-pod-autoscaler  New size: 10; reason: pods metric http_requests_per_second above target
  Normal  SuccessfulRescale  17m   horizontal-pod-autoscaler  New size: 7; reason: All metrics below target
  Normal  SuccessfulRescale  12m   horizontal-pod-autoscaler  New size: 5; reason: All metrics below target
  Normal  SuccessfulRescale  7m1s  horizontal-pod-autoscaler  New size: 4; reason: All metrics below target
  Normal  SuccessfulRescale  2m1s  horizontal-pod-autoscaler  New size: 3; reason: All metrics below targe

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python 运维开发:基于 Kubernetes RESTful API 实现 Deployment 创建 Kubernetes是一个开源的容器编排平台,它提供了一种便捷的方式来部署、扩展和管理容器化应用。在运维开发中,我们经常需要使用Kubernetes的API来创建Deployment。 首先,我们需要使用Python中的requests库来与Kubernetes的API进行交互。我们可以使用`requests.get()`或`requests.post()`等方法来发送HTTP请求,对Kubernetes进行操作。 接下来,我们需要构造正确的API地址和API请求数据。Kubernetes的API地址是基于集群的,我们可以通过访问`https://api.example.com`来得到API根地址。然后我们需要通过构造不同的路径来进行不同的操作,比如创建Deployment、查看Deployment等。 对于创建Deployment,我们可以使用POST请求来发送Deployment的定义。我们可以定义Deployment的名称、容器镜像、副本数量等信息,然后将这些信息转换为JSON格式,作为请求的数据体,发送到`/apis/apps/v1/namespaces/{namespace}/deployments`路径。 示例代码如下: ```python import requests import json def create_deployment(namespace, name, image, replicas): api_url = "https://api.example.com" endpoint = f"{api_url}/apis/apps/v1/namespaces/{namespace}/deployments" headers = {"Content-Type": "application/json"} data = { "apiVersion": "apps/v1", "kind": "Deployment", "metadata": { "name": name }, "spec": { "replicas": replicas, "selector": { "matchLabels": { "app": name } }, "template": { "metadata": { "labels": { "app": name } }, "spec": { "containers": [ { "name": name, "image": image, "ports": [ { "containerPort": 80 } ] } ] } } } } response = requests.post(endpoint, headers=headers, json=data) if response.status_code == 201: print(f"Deployment {name} created successfully.") else: print(f"There was an error creating Deployment {name}: {response.json()}") # 调用示例 create_deployment("default", "my-deployment", "my-image:latest", 3) ``` 以上代码中,我们定义了一个名为`create_deployment`的函数,它接受Namespace名称、Deployment名称、容器镜像和副本数量作为参数。然后,我们使用这些参数构造出Deployment的定义,并发送POST请求,创建Deployment。 最后,我们可以根据返回的响应状态码来判断Deployment是否成功创建。如果返回状态码为201,表示创建成功,否则表示创建失败,并打印出相应的错误信息。 通过这种方法,我们可以使用Python来基于Kubernetes的RESTful API实现Deployment的创建。这样,我们就可以在运维开发中使用Python来自动化操作Kubernetes集群,提高部署效率和管理灵活性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值