Skip to content

第十三部分:存储、调度与资源管理深度解析

本章深入讲解 PV/PVC/CSI 存储体系、调度器扩展机制、资源管理与自动伸缩,帮助你构建可靠的有状态应用和高效资源利用。


13.1 存储体系深度解析

13.1.1 PV/PVC/StorageClass 关系

用户创建 PVC("我要 10Gi 的存储")

StorageClass 的 Provisioner 自动创建 PV(动态供给)

PV 与 PVC 绑定(一对一关系)

Pod 通过 volume 引用 PVC

回收策略对比:

策略行为适用场景
RetainPV 释放后保留数据,需手动回收重要数据
DeletePVC 删除时同时删除 PV 和底层存储临时数据
Recycle已弃用(rm -rf)不推荐

13.1.2 CSI 插件架构

CSI(Container Storage Interface)三大组件:

Controller Plugin(运行在任意节点,通常 1 副本)
  → CreateVolume / DeleteVolume
  → ControllerPublishVolume(挂载到节点)
  → CreateSnapshot / DeleteSnapshot

Node Plugin(DaemonSet,每节点一个)
  → NodeStageVolume(格式化、挂载到暂存路径)
  → NodePublishVolume(bind mount 到 Pod 目录)
  → NodeUnpublishVolume / NodeUnstageVolume

常用 CSI 驱动:

CSI 驱动存储类型适用场景
Rook-Ceph分布式块/文件/对象私有云通用存储
OpenEBSLocal PV / 复制卷轻量级有状态应用
NFS-CSINFS共享读写(ReadWriteMany)
Longhorn块存储复制Rancher 生态

13.1.3 Volume 快照与克隆

yaml
# 创建快照类
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshotClass
metadata:
  name: csi-rbd-snapclass
driver: rook-ceph.rbd.csi.ceph.com
deletionPolicy: Delete
---
# 创建快照
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
  name: mysql-snapshot
spec:
  volumeSnapshotClassName: csi-rbd-snapclass
  source:
    persistentVolumeClaimName: mysql-data-pvc
---
# 从快照恢复新 PVC
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-data-restored
spec:
  dataSource:
    name: mysql-snapshot
    kind: VolumeSnapshot
    apiGroup: snapshot.storage.k8s.io
  accessModes: [ReadWriteOnce]
  resources:
    requests: { storage: 100Gi }

13.1.4 Local Volume vs Network Volume

特性Local VolumeNetwork Volume(Ceph/NFS)
性能极高(本地磁盘)中等(网络延迟)
数据持久性节点故障则丢失分布式冗余
Pod 调度约束绑定到特定节点任意节点可挂载
适用场景缓存、临时数据、高性能数据库生产数据库、需要迁移的应用

13.2 调度器深度解析

13.2.1 调度流程

SchedulingQueue

PreFilter(预检查:PVC 就绪?配额足够?)

Filter(过滤不可用节点)
  → NodeResourcesFit:资源是否足够
  → NodeAffinity:节点标签是否匹配
  → TaintToleration:能否容忍污点
  → PodTopologySpread:拓扑分布是否满足

Score(打分 0-100)
  → LeastAllocated:资源空闲多的节点优先
  → BalancedAllocation:CPU/Memory 使用率均衡
  → InterPodAffinity:与已有亲和 Pod 靠近

Reserve → Permit → PreBind → Bind

13.2.2 高级调度策略

yaml
# Pod 亲和性:与特定 Pod 调度到同一节点/区域
affinity:
  podAffinity:
    requiredDuringSchedulingIgnoredDuringExecution:
    - labelSelector:
        matchExpressions:
        - key: app
          operator: In
          values: [cache]
      topologyKey: topology.kubernetes.io/zone

# 污点容忍:让 Pod 调度到有特定污点的节点
tolerations:
- key: "dedicated"
  operator: "Equal"
  value: "gpu"
  effect: "NoSchedule"

# 优先级抢占:关键 Pod 可驱逐低优先级 Pod
priorityClassName: system-cluster-critical

13.2.3 自定义调度器

yaml
# 使用 KubeSchedulerConfiguration 配置调度插件
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: my-custom-scheduler
  plugins:
    score:
      enabled:
      - name: NodeResourcesFit
        weight: 5
      - name: InterPodAffinity
        weight: 3
    filter:
      enabled:
      - name: MyCustomFilterPlugin

13.3 资源管理与自动伸缩

13.3.1 LimitRange 与 ResourceQuota

yaml
# LimitRange:为 namespace 中的 Pod 设置默认资源限制
apiVersion: v1
kind: LimitRange
metadata:
  name: default-limits
  namespace: production
spec:
  limits:
  - default:           # 默认 limits
      cpu: "1"
      memory: 512Mi
    defaultRequest:    # 默认 requests
      cpu: 100m
      memory: 128Mi
    type: Container
---
# ResourceQuota:限制 namespace 的总资源用量
apiVersion: v1
kind: ResourceQuota
metadata:
  name: production-quota
spec:
  hard:
    requests.cpu: "100"
    requests.memory: 200Gi
    limits.cpu: "200"
    limits.memory: 400Gi
    pods: "500"

13.3.2 HPA / VPA / Cluster Autoscaler

HPA(Horizontal Pod Autoscaler)
  → 根据 CPU/Memory/自定义指标自动调整 Pod 副本数
  → 适用于无状态应用

VPA(Vertical Pod Autoscaler)
  → 自动调整 Pod 的 requests/limits
  → 适用于资源需求不确定的应用
  → 注意:HPA 和 VPA 不能同时对同一指标(如 CPU)生效

Cluster Autoscaler
  → 根据 Pending Pod 自动扩容节点
  → 根据节点利用率自动缩容节点
yaml
# HPA 配置示例
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  minReplicas: 3
  maxReplicas: 50
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Pods        # 自定义指标
    pods:
      metric:
        name: http_requests_per_second
      target:
        type: AverageValue
        averageValue: "1000"
  behavior:           # 伸缩行为控制
    scaleDown:
      stabilizationWindowSeconds: 300    # 缩容冷却 5 分钟
    scaleUp:
      stabilizationWindowSeconds: 60     # 扩容冷却 1 分钟

13.4 本章小结

核心概念关键要点
CSI 架构Controller Plugin + Node Plugin,分离控制面和数据面
快照与恢复VolumeSnapshot → 新 PVC,用于备份和克隆
调度流程PreFilter → Filter → Score → Reserve → Bind
自动伸缩HPA(水平)、VPA(垂直)、CA(集群),不能混用同一指标
资源管控LimitRange 设默认值,ResourceQuota 设上限

练习

  1. 部署 Rook-Ceph 并创建 VolumeSnapshot,从快照恢复数据验证完整性。
  2. 配置 HPA 使用自定义指标(如 QPS),使用 k6 压测观察自动扩缩。
  3. 在节点上设置污点,配置特定 Pod 的容忍策略实现专用节点调度。
  4. 对比 Local PV 和 Ceph RBD 的 IOPS 和延迟。

上一章:第十二部分:K8s 网络模型与 CNI 深度解析 下一章:第十四部分:K8s 安全与运维实战深度解析