Workstation Logo
产品
AI 实验室OpenAI代理Claude 代理Grok BotWorkstation CRM (WSL CRM)营销全部产品
AI 解决方案
AI 工作站AI SME Packages私有 AIGPU 集群边缘 AI企业 AI 实验室按行业分类的 AI
服务
Platform ModernisationDigital EngineeringData Foundations & AIAutonomous OperationsAI 咨询DevOps 自动化网络安全软件开发智能体构建MLOps 搭建
关于我们
合作伙伴客户案例
文章
文档
WSL ProxyRing PromoterWSL VaultJobshoutSysOps 24/7
博客
联系我们Login
Workstation

面向现代企业的 AI 工作站、AI 多智能体软件、GPU 基础设施和智能代理解决方案。

联系我们

AI 解决方案

AI 工作站AI SME Packages私有 AIGPU 集群边缘 AI企业 AI 实验室按行业分类的 AI

产品

全部产品WSL CRM 与 ERP营销OpenAI代理WSL ProxyRing PromoterWSL VaultJobshoutSysOps 24/7

公司

关于我们为什么选择Workstation合作伙伴客户案例价格联系

资源

文章文档博客搜索网站地图
英国办公室
77-79 Marlowes, Hemel Hempstead HP1 1LF路线指引 — 从 M25 外环伦敦 20 号出口驶出公司编号: 11641870周一至周五:上午 9:00 - 下午 6:00 GMT
+44 7515 356 146
比利时办公室
Workstation SRL, Rue Vanderkindere 34, 1180 Uccle, BrusselsBE 0751.518.683周一至周五:上午 9:00 - 下午 6:00 CET
+32 492 45 67 46
印度办公室
#159 Sector 9, Pocket 1, DDA Flats, 110077 Dwarka, New Delhi
+91 98881 98841

© 2026 Workstation AI。保留所有权利。

隐私Cookie服务条款网站地图

Loading blog...

Home / Blog
FlutterMobileApp

使用 Kubernetes 和 RKE2 扩展基础设施:生产深入探讨

RKE2 集群架构、水平和垂直自动扩展、高可用性、资源治理和 Prometheus/Grafana 可观察性的生产工程师指南

Balinder Walia2025年5月27日5 min read

在生产环境中运行 Kubernetes 集群是一回事。运行一个能够吸收不可预测的流量峰值、在控制平面故障中幸存、强制租户隔离并让您的运营团队清楚地了解系统每一层的网络——这是一项完全不同的挑战。 RKE2 是 Rancher 的下一代 Kubernetes 发行版,专为那些要求不可协商的环境而构建。

本文涵盖了生产级 RKE2 部署的整个生命周期:初始集群架构、Pod 和节点级别的自动缩放、高可用性控制平面、资源治理以及 Prometheus 和 Grafana 的可观察性。

为什么选择 RKE2?

RKE2 在三个关键领域区别于上游 Kubernetes 及其前身 RKE1。首先,它配备了开箱即用的 CIS Kubernetes 基准强化配置 - 准入控制器、审核日志记录、pod 安全性和 TLS 设置已预先配置为通过 CIS 1 级扫描,无需手动干预。其次,它符合 FIPS 140-2 标准,适合政府和受监管行业的部署。第三,它直接嵌入 Containerd 并附带自己的 CNI(Canal 或 Cilium,具体取决于您的配置选择),减少了您需要管理的外部依赖项的表面积。

RKE2 也适合气隙。安装捆绑包包括所有必需的容器映像,这在本地和边缘部署中非常重要,因为集群节点的互联网访问受到限制或不可能。

集群架构

生产 RKE2 集群分为服务器节点(运行控制平面和 etcd)和代理节点(运行工作负载)。为了实现高可用性,建议的拓扑是三个或五个服务器节点以及按工作负载类组织到节点池中的可变数量的代理节点。

RKE2 集群架构控制平面 (HA)主设备 1API 服务器etcd 领导者主设备 2API 服务器etcd followerMaster 3Scheduleretcd followerkubelet API工作节点(自动扩展池)Worker 1Pod Pod PodcontainerdWorker 2Pod Pod PodcontainerdWorker 3Pod Pod PodcontainerdWorker N可按需扩展...
# /etc/rancher/rke2/config.yaml (server node)
token: <shared-cluster-token>
tls-san:
  - 10.0.0.10          # VIP or load balancer address
  - k8s.internal.example.com
cni: cilium
cluster-cidr: 10.42.0.0/16
service-cidr: 10.43.0.0/16
etcd-expose-metrics: true
kube-apiserver-arg:
  - "audit-log-path=/var/log/kubernetes/audit.log"
  - "audit-log-maxage=30"
  - "audit-log-maxsize=100"
# /etc/rancher/rke2/config.yaml (agent node)
server: https://10.0.0.10:9345
token: <shared-cluster-token>
node-label:
  - "workload-class=general"
  - "topology.kubernetes.io/zone=eu-west-1a"

在第一个控制平面节点上安装服务器,然后使用相同的令牌和 VIP 地址加入其余服务器节点和所有代理节点。 RKE2 自动选举 etcd 领导者并管理法定人数。

# Install and start RKE2 server
curl -sfL https://get.rke2.io | INSTALL_RKE2_TYPE=server sh -
systemctl enable --now rke2-server.service

# Retrieve the node token for joining additional nodes
cat /var/lib/rancher/rke2/server/node-token

# Install and start RKE2 agent (on worker nodes)
curl -sfL https://get.rke2.io | INSTALL_RKE2_TYPE=agent sh -
systemctl enable --now rke2-agent.service

节点池和工作负载放置

并非所有工作负载都具有相同的资源配置文件。无状态 Web 服务与 GPU 推理作业、内存密集型分析工作负载或延迟敏感数据库具有不同的要求。将代理节点组织到具有不同标签和污点的池中,让 Kubernetes 将每个工作负载类别安排到适当大小的硬件上。

# Label a node pool for memory-intensive workloads
kubectl label nodes worker-mem-{1..4} workload-class=memory-optimised
kubectl taint nodes worker-mem-{1..4} workload-class=memory-optimised:NoSchedule

# Label a separate pool for general compute
kubectl label nodes worker-gen-{1..8} workload-class=general
# Deployment targeting the memory-optimised pool
apiVersion: apps/v1
kind: Deployment
metadata:
  name: analytics-engine
spec:
  template:
    spec:
      nodeSelector:
        workload-class: memory-optimised
      tolerations:
        - key: workload-class
          operator: Equal
          value: memory-optimised
          effect: NoSchedule
      containers:
        - name: analytics
          image: registry.internal/analytics:v2.3.1
          resources:
            requests:
              memory: "8Gi"
              cpu: "2"
            limits:
              memory: "16Gi"
              cpu: "4"

水平 Pod 自动缩放器

Horizontal Pod Autoscaler (HPA) 根据观察到的指标调整 Deployment 或 StatefulSet 的副本计数。 CPU 利用率是经典的触发器,但现代 HPA 配置还可以根据应用程序公开的自定义指标或消息队列深度等来源的外部指标进行扩展。

Kubernetes 自动扩展HPA - Pod 扩展PodPodPod+Pod基于 CPU/内存的扩展副本集群自动缩放器 - 节点缩放节点 13 Pod节点 23 个 Pod+节点待定添加/删除容量节点指标服务器CPU &内存利用率通过 Prometheus 自定义指标将数据馈送到 HPA 和 HPA集群自动缩放器

首先,确保 Metrics Server 正在运行 — RKE2 默认情况下不捆绑它。

kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
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: 65
    - type: Resource
      resource:
        name: memory
        target:
          type: Utilization
          averageUtilization: 70
  behavior:
    scaleDown:
      stabilizationWindowSeconds: 300  # wait 5 minutes before scaling down
      policies:
        - type: Percent
          value: 25
          periodSeconds: 60
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - type: Percent
          value: 100
          periodSeconds: 30

behavior模块对于稳定性至关重要。如果没有缩小的稳定窗口,短暂的流量下降就会过早地删除 Pod,从而在负载恢复时导致资源配置不足。非对称策略(积极扩大规模,保守缩小规模)是大多数生产工作负载的正确默认策略。

垂直 Pod 自动缩放器

垂直 Pod 自动缩放器 (VPA) 根据观察到的使用情况调整 CPU 和各个 Pod 上的内存请求的大小。它解决了一个常见问题:开发人员根据猜测设置初始资源请求,而这些值永远不会更新,从而导致浪费的过度配置或负载下的 OOMKilled pod。

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
  name: worker-vpa
  namespace: production
spec:
  targetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: background-worker
  updatePolicy:
    updateMode: "Auto"     # or "Off" to only view recommendations
  resourcePolicy:
    containerPolicies:
      - containerName: worker
        minAllowed:
          cpu: 100m
          memory: 256Mi
        maxAllowed:
          cpu: 4
          memory: 8Gi
        controlledResources: ["cpu", "memory"]

请注意,Auto模式下的 VPA 将逐出并重新启动 Pod 以应用新的资源值。对于无法中断正在进行的请求的服务,请在Off模式下运行 VPA 以生成建议,您可以在维护时段手动或通过 GitOps 工作流程应用这些建议。

重要提示:HPA 和 VPA 不应同时管理同一部署上的同一资源(CPU 或内存)。使用 HPA 进行 CPU 驱动的水平扩展,使用Off模式下的 VPA 来调整内存大小,或者使用KEDA进行需要细粒度控制的事件驱动扩展。

集群自动缩放器

Pod 自动缩放器在现有节点容量内工作。当该容量耗尽时(由于没有节点拥有足够的资源,pod 被困在Pending中),您需要 Cluster Autoscaler 来配置新节点。相反,当节点利用率明显不足时,Cluster Autoscaler 可以耗尽并停用它们,以降低基础设施成本。

在裸机或本地部署中,集群自动缩放器与您的基础设施配置层集成。对于云部署,AWS、GCP 和 Azure 等提供商提供本机节点组集成。以下示例显示了 AWS Auto Scaling 组的核心配置。

apiVersion: apps/v1
kind: Deployment
metadata:
  name: cluster-autoscaler
  namespace: kube-system
spec:
  template:
    spec:
      containers:
        - name: cluster-autoscaler
          image: registry.k8s.io/autoscaling/cluster-autoscaler:v1.29.0
          command:
            - ./cluster-autoscaler
            - --cloud-provider=aws
            - --nodes=2:10:k8s-general-worker-asg
            - --nodes=1:4:k8s-memory-worker-asg
            - --scale-down-delay-after-add=10m
            - --scale-down-unneeded-time=10m
            - --scale-down-utilization-threshold=0.5
            - --skip-nodes-with-local-storage=false
            - --expander=least-waste
          env:
            - name: AWS_REGION
              value: eu-west-1

--expander=least-waste选项告诉自动缩放器在容纳挂起的 Pod 后优先选择具有最少未使用资源的节点组,从而最大限度地降低成本。替代扩展器包括random、most-pods和priority。

高可用性控制平面

具有嵌入式 etcd 的三节点控制平面是最小可行的 HA 拓扑。 etcd 需要法定人数——大多数成员必须健康,集群才能接受写入。三个人可以容忍一次失败;有五个成员,你可以容忍两个。

控制平面节点必须位于负载平衡器后面。对于云部署,针对端口 6443(kube-apiserver)和 9345(RKE2 注册)的 TCP 负载均衡器效果很好。本地部署通常使用带有虚拟 IP 地址的 keepalived。

# keepalived.conf on control-plane nodes
vrrp_instance VI_1 {
    state MASTER        # BACKUP on the other two nodes
    interface eth0
    virtual_router_id 51
    priority 100        # 90 and 80 on the other two nodes
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass securepassword
    }
    virtual_ipaddress {
        10.0.0.10/24    # VIP used in tls-san and agent server address
    }
}

在任何控制平面操作后验证 etcd 是否正常。 RKE2 将etcdctl捆绑在/var/lib/rancher/rke2/bin/etcdctl上。

ETCDCTL_API=3 /var/lib/rancher/rke2/bin/etcdctl \
  --endpoints=https://127.0.0.1:2379 \
  --cacert=/var/lib/rancher/rke2/server/tls/etcd/server-ca.crt \
  --cert=/var/lib/rancher/rke2/server/tls/etcd/client.crt \
  --key=/var/lib/rancher/rke2/server/tls/etcd/client.key \
  endpoint health --cluster

资源配额和限制范围

在多租户集群中(不同的团队或应用程序共享相同的物理基础设施)ResourceQuotas 和 LimitRanges 是必不可少的护栏。 ResourceQuotas 对命名空间内的总资源消耗设置硬性上限。 LimitRanges 为各个容器设置默认值和最大值,防止配置错误的部署请求无限制的资源。

apiVersion: v1
kind: ResourceQuota
metadata:
  name: team-alpha-quota
  namespace: team-alpha
spec:
  hard:
    requests.cpu: "20"
    requests.memory: 40Gi
    limits.cpu: "40"
    limits.memory: 80Gi
    count/deployments.apps: "20"
    count/services: "15"
    persistentvolumeclaims: "10"
    requests.storage: 500Gi
apiVersion: v1
kind: LimitRange
metadata:
  name: team-alpha-limits
  namespace: team-alpha
spec:
  limits:
    - type: Container
      default:
        cpu: 500m
        memory: 512Mi
      defaultRequest:
        cpu: 100m
        memory: 128Mi
      max:
        cpu: "8"
        memory: 16Gi
    - type: PersistentVolumeClaim
      max:
        storage: 100Gi

应用 LimitRanges 可确保忘记指定资源请求的开发人员仍然获得合理的默认值,而不是请求零 CPU,否则会导致调度程序将 Pod 放置在任何位置,并可能导致同一节点上的其他工作负载匮乏。

使用 Prometheus 和 Grafana 进行监控

Kubernetes 集群中的

可观测性具有三个支柱:指标、日志和跟踪。 Prometheus 处理指标收集; Grafana 处理可视化。kube-prometheus-stackHelm 图表在单个命令中部署整个堆栈 — Prometheus Operator、警报管理器、Grafana、节点导出器和一套全面的预构建仪表板。

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

helm install kube-prometheus-stack prometheus-community/kube-prometheus-stack \
  --namespace monitoring \
  --create-namespace \
  --set prometheus.prometheusSpec.retention=30d \
  --set prometheus.prometheusSpec.storageSpec.volumeClaimTemplate.spec.storageClassName=longhorn \
  --set prometheus.prometheusSpec.storageSpec.volumeClaimTemplate.spec.resources.requests.storage=100Gi \
  --set grafana.adminPassword=<secure-password> \
  --set alertmanager.alertmanagerSpec.storage.volumeClaimTemplate.spec.resources.requests.storage=10Gi
当在服务器配置中设置etcd-expose-metrics: true时,

RKE2 会公开 etcd 指标。添加 ServiceMonitor,以便 Prometheus 抓取它们。

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: rke2-etcd
  namespace: monitoring
  labels:
    release: kube-prometheus-stack
spec:
  namespaceSelector:
    matchNames: [kube-system]
  selector:
    matchLabels:
      app.kubernetes.io/name: rke2-etcd
  endpoints:
    - port: metrics
      scheme: https
      tlsConfig:
        caFile: /etc/prometheus/secrets/etcd-client-cert/ca.crt
        certFile: /etc/prometheus/secrets/etcd-client-cert/client.crt
        keyFile: /etc/prometheus/secrets/etcd-client-cert/client.key

基本警报规则

预构建仪表板是一个起点,但根据您的环境调整的自定义警报规则允许待命工程师在用户注意到问题之前采取行动。

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  name: workload-alerts
  namespace: monitoring
  labels:
    release: kube-prometheus-stack
spec:
  groups:
    - name: pod-health
      rules:
        - alert: PodCrashLooping
          expr: rate(kube_pod_container_status_restarts_total[10m]) > 0.5
          for: 5m
          labels:
            severity: critical
          annotations:
            summary: "Pod {{ $labels.namespace }}/{{ $labels.pod }} is crash-looping"

        - alert: NodeMemoryPressure
          expr: |
            (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) < 0.1
          for: 2m
          labels:
            severity: warning
          annotations:
            summary: "Node {{ $labels.node }} memory below 10%"

        - alert: HPAMaxedOut
          expr: |
            kube_horizontalpodautoscaler_status_current_replicas
            == kube_horizontalpodautoscaler_spec_max_replicas
          for: 15m
          labels:
            severity: warning
          annotations:
            summary: "HPA {{ $labels.namespace }}/{{ $labels.horizontalpodautoscaler }} at maximum replicas"

HPAMaxedOut警报在实践中特别有价值。当 HPA 长时间固定在最大值时,意味着流量已超出当前上限。您要么需要提高最大值,要么增加节点池的容量——并且您想在下一个峰值之前而不是期间了解这一点。

生产最佳实践

Pod 中断预算

PodDisruptionBudget (PDB) 限制在节点耗尽等自愿中断期间,部署中可以同时不可用的 Pod 数量。如果没有 PDB,耗尽节点进行维护可能会使整个部署脱机。

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: api-server-pdb
  namespace: production
spec:
  minAvailable: 2       # or use maxUnavailable: 1
  selector:
    matchLabels:
      app: api-server

拓扑扩展约束

默认情况下,调度程序使用尽力而为算法在节点之间传播副本。拓扑分布约束为您提供了副本分布在可用区域或机架上的硬保证。

topologySpreadConstraints:
  - maxSkew: 1
    topologyKey: topology.kubernetes.io/zone
    whenUnsatisfiable: DoNotSchedule
    labelSelector:
      matchLabels:
        app: api-server

升级策略

RKE2 支持通过系统升级控制器进行滚动升级。您定义一个针对服务器或代理节点的计划并指定目标版本;控制器按顺序排空、升级和取消封锁节点。

apiVersion: upgrade.cattle.io/v1
kind: Plan
metadata:
  name: rke2-server-upgrade
  namespace: system-upgrade
spec:
  concurrency: 1
  cordon: true
  nodeSelector:
    matchExpressions:
      - { key: node-role.kubernetes.io/control-plane, operator: In, values: ["true"] }
  serviceAccountName: system-upgrade
  upgrade:
    image: rancher/rke2-upgrade
  version: v1.29.4+rke2r1

etcd 备份和恢复

RKE2 可以自动拍摄预定的 etcd 快照。确保它们写入集群外部的持久存储(S3 存储桶或远程 NFS 安装),而不是控制平面节点上的本地磁盘。

# /etc/rancher/rke2/config.yaml additions for automated snapshots
etcd-snapshot-schedule-cron: "0 */6 * * *"    # every 6 hours
etcd-snapshot-retention: 10
etcd-snapshot-dir: /mnt/nfs/etcd-snapshots

# Manual snapshot
rke2 etcd-snapshot save --name pre-upgrade-$(date +%Y%m%d)

# Restore from snapshot (run on a single server node with cluster stopped)
rke2 server --cluster-reset --cluster-reset-restore-path=/path/to/snapshot.db

结论

使用 RKE2 的

扩展基础设施不是单一的配置更改 - 它是一个必须一起设计和操作的互锁功能系统。水平 Pod 自动缩放可处理工作负载级别的短暂流量突发。垂直 Pod 自动缩放可以使资源请求随着时间的推移保持诚实。集群自动缩放器可确保底层节点容量跟踪 pod 自动缩放器的总需求。节点池和拓扑约束可确保工作负载落在正确的硬件上。资源配额和限制范围可以保护租户免受彼此的影响。 PodDisruptionBudgets 和拓扑扩展约束强化了可用性。 Prometheus 和 Grafana 使您的团队能够在发生故障之前检测到性能下降。

RKE2 之所以能在生产中占据一席之地,正是因为它交付的该堆栈的很大一部分是经过预硬化和预集成的。您的责任是了解这些旋钮,根据您的工作负载特征调整它们,并构建操作规程(运行手册、警报路由、升级节奏、备份验证),将配置良好的集群转变为真正可靠的平台。