Kubernetes资源限制与HPA自动伸缩:容器编排中的容量管理实战

Kubernetes资源管理的核心概念

Kubernetes容器编排中,资源管理是最基础也最容易踩坑的环节。Pod如果不设置资源限制,单个异常Pod可能耗尽节点资源导致整机不可用,进而引发雪崩。Kubernetes通过requests和limits两个维度实现资源隔离:requests决定调度时的资源分配,limits限制运行时的资源使用上限。

DevOps实践中,资源管理不规范导致的典型故障:某个Pod内存泄漏不断增长,因为没有limit限制,逐步吃光节点内存,kubelet触发OOM killing全节点Pod,业务大面积受影响。这类问题完全可以通过规范的资源配置避免。

Pod资源Requests与Limits配置

资源配置写在容器的resources字段中:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: api-server
spec:
  replicas: 3
  selector:
    matchLabels:
      app: api-server
  template:
    metadata:
      labels:
        app: api-server
    spec:
      containers:
      - name: api
        image: registry.example.com/api-server:v2.1.0
        ports:
        - containerPort: 8080
        resources:
          requests:
            cpu: "500m"        # 0.5核
            memory: "512Mi"
          limits:
            cpu: "1000m"       # 1核
            memory: "1Gi"
        # 配置存活探针,配合资源限制实现自动恢复
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5

几个配置原则:

requests和limits的差距不要过大。CPU的limit通常是request的2倍,内存limit是request的1.5倍。差距过大导致调度效率低下——调度器按requests分配,实际使用远超requests时节点超卖严重。差距过小则没有弹性空间,流量峰值时频繁被throttle。

CPU是可压缩资源(compressible),超限时容器被throttle变慢但不被杀死。内存是不可压缩资源(incompressible),超限时容器被OOM Killed。所以内存limit必须大于实际峰值使用量,否则会频繁重启。

查看容器资源使用情况:

# 查看节点资源分配情况
kubectl describe node node-01 | grep -A 10 "Allocated resources"

# 查看Pod资源使用(需要metrics-server)
kubectl top pods -n production
kubectl top pods -n production --sort-by=memory

# 查看Pod是否被throttle(CPU限流)
kubectl get --raw "/apis/metrics.k8s.io/v1beta1/namespaces/production/pods/api-server-xxx"

LimitRange默认资源限制

团队中不是每个人都会认真配置resources。配置LimitRange为命名空间设置默认值和约束:

apiVersion: v1
kind: LimitRange
metadata:
  name: default-limits
  namespace: production
spec:
  limits:
  - type: Container
    default:              # 未设置limits时的默认值
      cpu: "1"
      memory: "1Gi"
    defaultRequest:       # 未设置requests时的默认值
      cpu: "200m"
      memory: "256Mi"
    max:                  # 允许设置的最大值
      cpu: "4"
      memory: "8Gi"
    min:                  # 允许设置的最小值
      cpu: "50m"
      memory: "64Mi"
    maxLimitRequestRatio: # limits/requests最大比例
      cpu: 4
      memory: 2

HPA水平Pod自动伸缩配置

HPA(Horizontal Pod Autoscaler)根据CPU/内存使用率或自定义指标自动调整Pod副本数。这是处理流量波动的核心机制。

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api-server-hpa
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api-server
  minReplicas: 3
  maxReplicas: 20
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70    # CPU使用率目标70%
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80    # 内存使用率目标80%
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0    # 扩容立即执行
      policies:
      - type: Percent
        value: 100                      # 每次最多扩容100%
        periodSeconds: 30
      - type: Pods
        value: 4                        # 或每次最多加4个Pod
        periodSeconds: 30
      selectPolicy: Max
    scaleDown:
      stabilizationWindowSeconds: 300   # 缩容需要5分钟稳定期
      policies:
      - type: Percent
        value: 10                       # 每次最多缩容10%
        periodSeconds: 60

behavior配置是HPA调优的关键。scaleUp的stabilizationWindowSeconds设为0意味着流量增长时立即扩容,避免响应延迟。scaleDown的stabilizationWindowSeconds设为300秒,防止流量短暂波动导致频繁缩容再扩容的抖动。

Custom Metrics与自定义指标伸缩

CPU和内存使用率不能覆盖所有场景。比如IO密集型服务CPU使用率不高但请求队列积压,按CPU伸缩无法及时响应。需要基于自定义指标伸缩。

部署Prometheus Adapter将Prometheus指标暴露给Kubernetes自定义指标API:

# Prometheus Adapter配置文件adapter-config.yaml
# 将Prometheus中的http_requests_per_second指标映射为自定义指标
- seriesQuery: 'http_requests_total{namespace!="",pod!=""}'
  resources:
    overrides:
      namespace: {resource: "namespace"}
      pod: {resource: "pod"}
  name:
    matches: "^(.*)_total"
    as: "${1}_per_second"
  metricsQuery: 'sum(rate(<<.Series>>{<<.LabelMatchers>>}[2m])) by (<<.GroupBy>>)'

HPA使用自定义指标:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: api-server-custom-hpa
  namespace: production
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: api-server
  minReplicas: 3
  maxReplicas: 30
  metrics:
  - type: Pods
    pods:
      metric:
        name: http_requests_per_second
      target:
        type: AverageValue
        averageValue: "500"    # 每个Pod目标处理500 QPS

监控告警体系与故障应急响应

HPA伸缩行为需要纳入监控告警体系。关键告警规则配置:

# Prometheus告警规则
groups:
- name: hpa-alerts
  rules:
  - alert: HPAReachedMaxReplicas
    expr: kube_horizontalpodautoscaler_status_current_replicas == kube_horizontalpodautoscaler_spec_max_replicas
    for: 10m
    labels:
      severity: warning
    annotations:
      summary: "HPA {{ $labels.horizontalpodautoscaler }} 已达到最大副本数"
      description: "当前副本数已达上限 {{ $value }},可能需要扩容节点或优化服务"

  - alert: PodRestartedByOOM
    expr: increase(kube_pod_container_status_restarts_total{reason="OOMKilled"}[1h]) > 0
    labels:
      severity: critical
    annotations:
      summary: "Pod {{ $labels.pod }} 因OOM重启"
      description: "内存limit设置过低或存在内存泄漏"

  - alert: PodCPUThrottling
    expr: rate(container_cpu_cfs_throttled_seconds_total[5m]) > 0.1
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "Pod {{ $labels.pod }} CPU被限流"
      description: "CPU limit设置过低,影响响应延迟"

故障应急响应流程:收到HPA达到最大副本数告警时,第一步检查Pod资源使用分布,确认是否某一类请求导致资源消耗异常;第二步查看节点资源余量,if节点资源不足,需要扩容节点(Cluster Autoscaler或手动);第三步评估是否为单次突发流量,如果持续性增长需要调整maxReplicas上限。

混沌工程视角的验证方法:定期注入故障测试HPA是否按预期工作。用Chaos Mesh模拟节点宕机,观察Pod是否自动迁移和HPA是否正确响应。这类演练在生产环境低峰期执行,能提前暴露配置问题。

CI/CD流水线中应该加入资源配置校验。用kube-score或polaris等静态分析工具检查YAML文件中是否设置了resources、是否配置探针、HPA的min/max是否合理。把资源管理规范固化到流水线中,比靠人工review可靠得多。

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/kubernetes-zi-yuan-xian-zhi-yu-hpa-zi-dong-shen-suo-rong-qi/

(0)
小编小编
上一篇 16小时前
下一篇 16小时前

相关推荐