Kubernetes高可用集群部署与故障自愈实战指南

Kubernetes集群高可用部署的架构前提

Kubernetes容器编排已成为生产环境的事实标准,但单集群的可用性天花板取决于控制平面的设计。一个单Master节点的K8s集群,API Server故障即意味着整个管控能力丢失——调度停止、扩缩容失灵、故障自愈机制瘫痪。高可用不是可选项,是生产集群的底线要求。

核心控制平面组件包括:API Server、etcd、Controller Manager、Scheduler。高可用的关键在于etcd集群的可用性——etcd是K8s的唯一状态存储,一旦etcd不可用,整个集群将无法响应任何写操作。

etcd高可用集群搭建与调优

etcd采用Raft协议实现分布式一致性,推荐奇数节点部署(3或5节点),容忍 (N-1)/2 个节点故障。

三节点etcd集群部署

# 在每个节点上配置etcd
# 节点1: 10.0.0.1
# 节点2: 10.0.0.2
# 节点3: 10.0.0.3

cat > /etc/etcd/etcd.conf.yml << 'EOF'
name: etcd-node1
data-dir: /var/lib/etcd
listen-client-urls: https://10.0.0.1:2379
listen-peer-urls: https://10.0.0.1:2380
advertise-client-urls: https://10.0.0.1:2379
advertise-peer-urls: https://10.0.0.1:2380
initial-cluster: etcd-node1=https://10.0.0.1:2380,etcd-node2=https://10.0.0.2:2380,etcd-node3=https://10.0.0.3:2380
initial-cluster-token: etcd-ha-cluster
initial-cluster-state: new
client-transport-security:
  cert-file: /etc/etcd/certs/server.crt
  key-file: /etc/etcd/certs/server.key
  client-cert-auth: true
  trusted-ca-file: /etc/etcd/certs/ca.crt
peer-transport-security:
  cert-file: /etc/etcd/certs/peer.crt
  key-file: /etc/etcd/certs/peer.key
  client-cert-auth: true
  trusted-ca-file: /etc/etcd/certs/ca.crt
auto-compaction-mode: periodic
auto-compaction-retention: "1h"
snapshot-count: 10000
quota-backend-bytes: 8589934592
EOF

etcd性能调优关键参数

# etcd写入延迟对K8s API响应影响极大
# 关键监控指标:
# - etcd_disk_wal_fsync_duration_seconds:WAL写入延迟,P99应 < 10ms
# - etcd_mvcc_db_total_size_in_bytes:数据库大小,不应超过8GB
# - etcd_server_has_leader:是否有leader,0表示无leader

# WAL和数据分盘存放,避免IO争抢
# 在systemd unit中配置:
--data-dir=/data/etcd/main \
--wal-dir=/data/etcd/wal

# 定期碎片整理(避免DB膨胀)
etcdctl defrag --cluster=true --command-timeout=60s

API Server负载均衡与故障转移

多API Server实例通过负载均衡器对外暴露统一端点。推荐架构:

# HAProxy配置示例
frontend k8s-api
    bind 10.0.0.100:6443
    mode tcp
    option tcplog
    default_backend k8s-api-servers

backend k8s-api-servers
    mode tcp
    option httpchk GET /healthz
    http-check expect status 200
    balance leastconn
    server master1 10.0.0.1:6443 check check-ssl verify none inter 5s fall 3 rise 2
    server master2 10.0.0.2:6443 check check-ssl verify none inter 5s fall 3 rise 2
    server master3 10.0.0.3:6443 check check-ssl verify none inter 5s fall 3 rise 2

关键设计决策:

  • 使用TCP模式而非HTTP模式,避免解析开销
  • 健康检查间隔5秒,连续3次失败摘除,2次成功恢复
  • Keepalived做VIP漂移,确保LB自身高可用

故障自愈:Kubernetes自动修复机制

节点级故障自愈

当Worker节点不可达时,K8s的Node Lifecycle Controller会自动标记节点为NotReady,并在指定时间后将该节点上的Pod驱逐到其他节点。

# kube-controller-manager配置
--node-monitor-grace-period=40s     # 节点失联多久标记NotReady
--pod-eviction-timeout=300s          # NotReady多久后开始驱逐Pod
--node-signature-profile=AutoRepair # 启用自动修复(1.30+特性)

Pod级故障自愈

Deployment/StatefulSet自带的副本管理已经能处理大部分Pod级故障。关键配置:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-server
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1        # 同时最多1个不可用
      maxSurge: 1              # 滚动更新时最多多1个
  template:
    spec:
      containers:
      - name: app
        image: app:v2.1.0
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          periodSeconds: 10
          failureThreshold: 3    # 连续3次失败重启容器
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: DoNotSchedule
        labelSelector:
          matchLabels:
            app: app-server

应用级自愈:运维自动化控制器

K8s原生机制无法处理所有故障场景。常见补充方案:

# 使用KEDA实现基于自定义指标的自动伸缩
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: queue-consumer-scaler
spec:
  scaleTargetRef:
    name: queue-consumer
  minReplicaCount: 2
  maxReplicaCount: 20
  triggers:
  - type: rabbitmq
    metadata:
      queueName: task_queue
      host: amqp://rabbitmq:5672
      queueLength: "100"    # 每100条消息扩1个副本

混沌工程:主动验证高可用能力

高可用架构需要主动验证。混沌工程不是"故意搞破坏",而是"在可控范围内注入故障,验证系统韧性"。

Chaos Mesh故障注入

# Pod Kill实验:验证应用能自动恢复
apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
  name: app-pod-kill
spec:
  action: pod-kill
  mode: one
  selector:
    namespaces:
      - production
    labelSelectors:
      app: app-server
  scheduler:
    cron: "@every 300s"    # 每5分钟随机杀一个Pod

---
# 网络延迟注入:验证超时和重试机制
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
  name: api-latency
spec:
  action: delay
  mode: one
  selector:
    namespaces:
      - production
    labelSelectors:
      app: app-server
  delay:
    latency: "500ms"
    jitter: "100ms"
  duration: "60s"

故障演练SOP

  1. 明确假设:"应用在单个Pod被Kill后5秒内恢复就绪"
  2. 注入故障:创建PodChaos资源
  3. 观察指标:监控dashboard追踪就绪副本数、请求成功率、P99延迟
  4. 验证假设:检查恢复时间是否在预期内
  5. 记录差异:如果恢复超预期,定位根因并修复

CI/CD流水线与K8s集成的故障预防

高可用不只是运行时的能力,还体现在发布过程中的预防措施。

# GitOps模式:ArgoCD自动同步
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: app-server
spec:
  source:
    repoURL: https://git.example.com/k8s-manifests.git
    targetRevision: main
    path: production/app-server
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  syncPolicy:
    automated:
      prune: true
      selfHeal: true           # 自动修复配置漂移
      allowEmpty: false
    syncOptions:
    - CreateNamespace=false
    retry:
      limit: 3
      backoff:
        duration: 5s
        factor: 2
        maxDuration: 3m

监控告警体系设计

高可用集群的监控要分层覆盖:

# Prometheus关键告警规则
groups:
- name: k8s-ha-alerts
  rules:
  - alert: EtcdLeaderUnavailable
    expr: etcd_server_has_leader == 0
    for: 1m
    labels:
      severity: critical
    annotations:
      summary: "etcd集群无leader,K8s控制平面不可用"

  - alert: K8sAPIServerDown
    expr: up{job="kubernetes-apiservers"} == 0
    for: 2m
    labels:
      severity: critical

  - alert: NodeNotReady
    expr: kube_node_status_condition{condition="Ready",status="true"} == 0
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "节点 {{ $labels.node }} NotReady超过5分钟"

应急响应手册:常见故障快速处置

场景一:etcd集群丢失一个节点

# 1. 确认剩余节点状态
etcdctl endpoint status --cluster -w table

# 2. 移除故障节点
etcdctl member remove 

# 3. 修复或替换故障节点后重新加入
etcdctl member add etcd-node1 --peer-urls=https://10.0.0.1:2380

# 4. 在新节点上启动etcd,使用 existing 状态
initial-cluster-state: existing

场景二:API Server全部不可达

# 1. 检查etcd是否可用
etcdctl endpoint health --cluster

# 2. 如果etcd正常,检查API Server日志
journalctl -u kube-apiserver --since "5 minutes ago"

# 3. 常见原因:证书过期
openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -dates

# 4. 紧急处理:临时重启API Server
systemctl restart kube-apiserver

场景三:Node网络分区

# 确认分区状态
kubectl get nodes -o wide
kubectl describe node  | grep -A5 Conditions

# 隔离分区节点
kubectl cordon 
kubectl drain  --ignore-daemonsets --delete-emptydir-data

# 网络恢复后解除隔离
kubectl uncordon 

高可用集群的运维不是一次性配置,而是持续验证和迭代的过程。定期做故障演练、持续完善监控覆盖、保持应急响应手册更新,这三件事比任何单点优化都重要。

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/kubernetes-gao-ke-yong-ji-qun-bu-shu-yu-gu-zhang-zi-yu-shi/

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

相关推荐

Kubernetes高可用集群部署与故障自愈实战指南

Kubernetes集群高可用部署的架构前提

Kubernetes容器编排已成为生产环境的事实标准,但单集群的可用性天花板取决于控制平面的设计。一个单Master节点的K8s集群,API Server故障即意味着整个管控能力丢失——调度停止、扩缩容失灵、故障自愈机制瘫痪。高可用不是可选项,是生产集群的底线要求。

核心控制平面组件包括:API Server、etcd、Controller Manager、Scheduler。高可用的关键在于etcd集群的可用性——etcd是K8s的唯一状态存储,一旦etcd不可用,整个集群将无法响应任何写操作。

etcd高可用集群搭建与调优

etcd采用Raft协议实现分布式一致性,推荐奇数节点部署(3或5节点),容忍 (N-1)/2 个节点故障。

三节点etcd集群部署

# 在每个节点上配置etcd
# 节点1: 10.0.0.1
# 节点2: 10.0.0.2
# 节点3: 10.0.0.3

cat > /etc/etcd/etcd.conf.yml << 'EOF'
name: etcd-node1
data-dir: /var/lib/etcd
listen-client-urls: https://10.0.0.1:2379
listen-peer-urls: https://10.0.0.1:2380
advertise-client-urls: https://10.0.0.1:2379
advertise-peer-urls: https://10.0.0.1:2380
initial-cluster: etcd-node1=https://10.0.0.1:2380,etcd-node2=https://10.0.0.2:2380,etcd-node3=https://10.0.0.3:2380
initial-cluster-token: etcd-ha-cluster
initial-cluster-state: new
client-transport-security:
  cert-file: /etc/etcd/certs/server.crt
  key-file: /etc/etcd/certs/server.key
  client-cert-auth: true
  trusted-ca-file: /etc/etcd/certs/ca.crt
peer-transport-security:
  cert-file: /etc/etcd/certs/peer.crt
  key-file: /etc/etcd/certs/peer.key
  client-cert-auth: true
  trusted-ca-file: /etc/etcd/certs/ca.crt
auto-compaction-mode: periodic
auto-compaction-retention: "1h"
snapshot-count: 10000
quota-backend-bytes: 8589934592
EOF

etcd性能调优关键参数

# etcd写入延迟对K8s API响应影响极大
# 关键监控指标:
# - etcd_disk_wal_fsync_duration_seconds:WAL写入延迟,P99应 < 10ms
# - etcd_mvcc_db_total_size_in_bytes:数据库大小,不应超过8GB
# - etcd_server_has_leader:是否有leader,0表示无leader

# WAL和数据分盘存放,避免IO争抢
# 在systemd unit中配置:
--data-dir=/data/etcd/main \
--wal-dir=/data/etcd/wal

# 定期碎片整理(避免DB膨胀)
etcdctl defrag --cluster=true --command-timeout=60s

API Server负载均衡与故障转移

多API Server实例通过负载均衡器对外暴露统一端点。推荐架构:

# HAProxy配置示例
frontend k8s-api
    bind 10.0.0.100:6443
    mode tcp
    option tcplog
    default_backend k8s-api-servers

backend k8s-api-servers
    mode tcp
    option httpchk GET /healthz
    http-check expect status 200
    balance leastconn
    server master1 10.0.0.1:6443 check check-ssl verify none inter 5s fall 3 rise 2
    server master2 10.0.0.2:6443 check check-ssl verify none inter 5s fall 3 rise 2
    server master3 10.0.0.3:6443 check check-ssl verify none inter 5s fall 3 rise 2

关键设计决策:

  • 使用TCP模式而非HTTP模式,避免解析开销
  • 健康检查间隔5秒,连续3次失败摘除,2次成功恢复
  • Keepalived做VIP漂移,确保LB自身高可用

故障自愈:Kubernetes自动修复机制

节点级故障自愈

当Worker节点不可达时,K8s的Node Lifecycle Controller会自动标记节点为NotReady,并在指定时间后将该节点上的Pod驱逐到其他节点。

# kube-controller-manager配置
--node-monitor-grace-period=40s     # 节点失联多久标记NotReady
--pod-eviction-timeout=300s          # NotReady多久后开始驱逐Pod
--node-signature-profile=AutoRepair # 启用自动修复(1.30+特性)

Pod级故障自愈

Deployment/StatefulSet自带的副本管理已经能处理大部分Pod级故障。关键配置:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-server
spec:
  replicas: 3
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1        # 同时最多1个不可用
      maxSurge: 1              # 滚动更新时最多多1个
  template:
    spec:
      containers:
      - name: app
        image: app:v2.1.0
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          periodSeconds: 10
          failureThreshold: 3    # 连续3次失败重启容器
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
      topologySpreadConstraints:
      - maxSkew: 1
        topologyKey: topology.kubernetes.io/zone
        whenUnsatisfiable: DoNotSchedule
        labelSelector:
          matchLabels:
            app: app-server

应用级自愈:运维自动化控制器

K8s原生机制无法处理所有故障场景。常见补充方案:

# 使用KEDA实现基于自定义指标的自动伸缩
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
  name: queue-consumer-scaler
spec:
  scaleTargetRef:
    name: queue-consumer
  minReplicaCount: 2
  maxReplicaCount: 20
  triggers:
  - type: rabbitmq
    metadata:
      queueName: task_queue
      host: amqp://rabbitmq:5672
      queueLength: "100"    # 每100条消息扩1个副本

混沌工程:主动验证高可用能力

高可用架构需要主动验证。混沌工程不是"故意搞破坏",而是"在可控范围内注入故障,验证系统韧性"。

Chaos Mesh故障注入

# Pod Kill实验:验证应用能自动恢复
apiVersion: chaos-mesh.org/v1alpha1
kind: PodChaos
metadata:
  name: app-pod-kill
spec:
  action: pod-kill
  mode: one
  selector:
    namespaces:
      - production
    labelSelectors:
      app: app-server
  scheduler:
    cron: "@every 300s"    # 每5分钟随机杀一个Pod

---
# 网络延迟注入:验证超时和重试机制
apiVersion: chaos-mesh.org/v1alpha1
kind: NetworkChaos
metadata:
  name: api-latency
spec:
  action: delay
  mode: one
  selector:
    namespaces:
      - production
    labelSelectors:
      app: app-server
  delay:
    latency: "500ms"
    jitter: "100ms"
  duration: "60s"

故障演练SOP

  1. 明确假设:"应用在单个Pod被Kill后5秒内恢复就绪"
  2. 注入故障:创建PodChaos资源
  3. 观察指标:监控dashboard追踪就绪副本数、请求成功率、P99延迟
  4. 验证假设:检查恢复时间是否在预期内
  5. 记录差异:如果恢复超预期,定位根因并修复

CI/CD流水线与K8s集成的故障预防

高可用不只是运行时的能力,还体现在发布过程中的预防措施。

# GitOps模式:ArgoCD自动同步
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  name: app-server
spec:
  source:
    repoURL: https://git.example.com/k8s-manifests.git
    targetRevision: main
    path: production/app-server
  destination:
    server: https://kubernetes.default.svc
    namespace: production
  syncPolicy:
    automated:
      prune: true
      selfHeal: true           # 自动修复配置漂移
      allowEmpty: false
    syncOptions:
    - CreateNamespace=false
    retry:
      limit: 3
      backoff:
        duration: 5s
        factor: 2
        maxDuration: 3m

监控告警体系设计

高可用集群的监控要分层覆盖:

# Prometheus关键告警规则
groups:
- name: k8s-ha-alerts
  rules:
  - alert: EtcdLeaderUnavailable
    expr: etcd_server_has_leader == 0
    for: 1m
    labels:
      severity: critical
    annotations:
      summary: "etcd集群无leader,K8s控制平面不可用"

  - alert: K8sAPIServerDown
    expr: up{job="kubernetes-apiservers"} == 0
    for: 2m
    labels:
      severity: critical

  - alert: NodeNotReady
    expr: kube_node_status_condition{condition="Ready",status="true"} == 0
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: "节点 {{ $labels.node }} NotReady超过5分钟"

应急响应手册:常见故障快速处置

场景一:etcd集群丢失一个节点

# 1. 确认剩余节点状态
etcdctl endpoint status --cluster -w table

# 2. 移除故障节点
etcdctl member remove 

# 3. 修复或替换故障节点后重新加入
etcdctl member add etcd-node1 --peer-urls=https://10.0.0.1:2380

# 4. 在新节点上启动etcd,使用 existing 状态
initial-cluster-state: existing

场景二:API Server全部不可达

# 1. 检查etcd是否可用
etcdctl endpoint health --cluster

# 2. 如果etcd正常,检查API Server日志
journalctl -u kube-apiserver --since "5 minutes ago"

# 3. 常见原因:证书过期
openssl x509 -in /etc/kubernetes/pki/apiserver.crt -noout -dates

# 4. 紧急处理:临时重启API Server
systemctl restart kube-apiserver

场景三:Node网络分区

# 确认分区状态
kubectl get nodes -o wide
kubectl describe node  | grep -A5 Conditions

# 隔离分区节点
kubectl cordon 
kubectl drain  --ignore-daemonsets --delete-emptydir-data

# 网络恢复后解除隔离
kubectl uncordon 

高可用集群的运维不是一次性配置,而是持续验证和迭代的过程。定期做故障演练、持续完善监控覆盖、保持应急响应手册更新,这三件事比任何单点优化都重要。

原创文章,作者:小编,如若转载,请注明出处:https://www.yunthe.com/kubernetes-gao-ke-yong-ji-qun-bu-shu-yu-gu-zhang-zi-yu-shi/

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

相关推荐