活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

Kubernetes集群健康检查全攻略从监控指标到故障维护的完整指南帮助运维人员快速定位问题保障系统高可用

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-18 15:30:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

Kubernetes作为容器编排领域的领导者,已被广泛应用于企业级应用部署和管理。随着集群规模的增长和复杂性的提升,确保集群的健康状态变得至关重要。一个健康的Kubernetes集群不仅能够提供稳定的服务,还能在出现问题时快速恢复,保障业务连续性。本文将全面介绍Kubernetes集群健康检查的方法、工具和最佳实践,帮助运维人员构建完善的监控体系,快速定位并解决问题,确保系统的高可用性。

Kubernetes集群监控基础

核心组件和架构

在深入监控之前,我们需要了解Kubernetes集群的核心组件及其架构。一个典型的Kubernetes集群由控制平面(Control Plane)和工作节点(Worker Nodes)组成。

控制平面组件包括:

• kube-apiserver:集群的统一入口,处理RESTful操作
• etcd:分布式键值存储,保存集群所有状态数据
• kube-scheduler:负责Pod调度决策
• kube-controller-manager:运行控制器进程
• cloud-controller-manager:与云服务提供商交互的组件

工作节点组件包括:

• kubelet:确保容器在Pod中运行
• kube-proxy:维护节点网络规则
• 容器运行时:如Docker、containerd等

了解这些组件有助于我们确定监控的关键点和指标。

常见监控指标

Kubernetes集群的监控指标可以分为以下几类:

• CPU使用率:节点和Pod的CPU消耗情况
• 内存使用率:节点和Pod的内存消耗情况
• 磁盘使用率:节点磁盘空间使用情况
• 网络I/O:节点和Pod的网络流量

• 组件运行状态:各核心组件是否正常运行
• API服务器响应时间:API请求的处理延迟
• etcd性能指标:etcd的读写延迟和存储情况

• Pod状态:运行中、待定、失败、成功等状态的数量
• 节点状态:就绪、未就绪、不可达等状态的数量
• Deployment状态:副本数量、可用副本数量、更新状态等
• PVC状态:绑定状态、容量使用情况等

• HTTP请求成功率:应用服务的HTTP响应状态码统计
• 请求延迟:应用服务的响应时间
• 错误率:应用服务的错误请求比例

监控工具与方案

Kubernetes内置监控能力

Kubernetes提供了一些内置的监控能力,可以帮助我们了解集群的基本状态。

kubectl是Kubernetes的命令行工具,通过它可以获取集群的各种状态信息。
  1. # 查看集群组件状态
  2. kubectl get componentstatuses
  3. # 查看节点状态
  4. kubectl get nodes
  5. # 查看所有命名空间中的Pod状态
  6. kubectl get pods --all-namespaces
  7. # 查看特定资源详细信息
  8. kubectl describe nodes <node-name>
  9. kubectl describe pods <pod-name> -n <namespace>
  10. # 查看资源使用情况
  11. kubectl top nodes
  12. kubectl top pods --all-namespaces
复制代码

Metrics Server是Kubernetes内置的资源使用数据收集器,它可以收集节点和Pod的CPU和内存使用情况。

安装Metrics Server:
  1. kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
复制代码

安装完成后,可以使用kubectl top命令查看资源使用情况。

第三方监控工具

Prometheus是一个开源的监控和告警系统,特别适合于Kubernetes环境。Grafana则是一个可视化工具,可以创建丰富的仪表板。

部署Prometheus和Grafana:

可以使用Helm来快速部署:
  1. # 添加Helm仓库
  2. helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
  3. helm repo update
  4. # 安装Prometheus
  5. helm install prometheus prometheus-community/kube-prometheus-stack
  6. # 查看部署状态
  7. kubectl get pods -n default
复制代码

配置Prometheus监控Kubernetes:

Prometheus可以通过ServiceMonitor资源自动发现和监控Kubernetes资源。以下是一个示例ServiceMonitor配置:
  1. apiVersion: monitoring.coreos.com/v1
  2. kind: ServiceMonitor
  3. metadata:
  4.   name: example-app
  5.   namespace: monitoring
  6. spec:
  7.   selector:
  8.     matchLabels:
  9.       app: example-app
  10.   endpoints:
  11.   - port: web
  12.     interval: 30s
  13.     path: /metrics
复制代码

Grafana仪表板:

Grafana提供了许多预置的Kubernetes监控仪表板,可以直接导入使用。一些常用的仪表板ID包括:

• 315:Kubernetes Cluster Monitoring
• 6417:Kubernetes Compute Resources / Pod
• 11074:Kubernetes API Server

除了Prometheus和Grafana,还有其他一些优秀的监控工具:

1. Datadog:提供全面的云原生监控解决方案
2. Sysdig:专注于容器安全和性能监控
3. New Relic:全栈可观测性平台
4. Elastic Stack (ELK):用于日志收集、搜索和分析

健康检查策略

Pod健康检查

Kubernetes提供了两种Pod健康检查机制:存活探针(Liveness Probe)和就绪探针(Readiness Probe)。

存活探针用于确定容器是否正在运行。如果探针失败,kubelet会杀死容器,并根据重启策略进行重启。

存活探针示例:
  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4.   name: liveness-pod
  5. spec:
  6.   containers:
  7.   - name: liveness-container
  8.     image: k8s.gcr.io/busybox
  9.     args:
  10.     - /bin/sh
  11.     - -c
  12.     - touch /tmp/healthy; sleep 30; rm -rf /tmp/healthy; sleep 600
  13.     livenessProbe:
  14.       exec:
  15.         command:
  16.         - cat
  17.         - /tmp/healthy
  18.       initialDelaySeconds: 5
  19.       periodSeconds: 5
复制代码

就绪探针用于确定容器是否准备好接收流量。如果探针失败,Pod将从服务的负载均衡中移除。

就绪探针示例:
  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4.   name: readiness-pod
  5. spec:
  6.   containers:
  7.   - name: readiness-container
  8.     image: k8s.gcr.io/busybox
  9.     args:
  10.     - /bin/sh
  11.     - -c
  12.     - touch /tmp/ready; sleep 30; rm -rf /tmp/ready; sleep 600
  13.     readinessProbe:
  14.       exec:
  15.         command:
  16.         - cat
  17.         - /tmp/ready
  18.       initialDelaySeconds: 5
  19.       periodSeconds: 5
复制代码

启动探针用于确定容器应用是否已经启动。在启动探针成功之前,其他探针不会生效。

启动探针示例:
  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4.   name: startup-pod
  5. spec:
  6.   containers:
  7.   - name: startup-container
  8.     image: k8s.gcr.io/busybox
  9.     args:
  10.     - /bin/sh
  11.     - -c
  12.     - sleep 60; touch /tmp/started; sleep 600
  13.     startupProbe:
  14.       exec:
  15.         command:
  16.         - cat
  17.         - /tmp/started
  18.       failureThreshold: 30
  19.       periodSeconds: 10
复制代码

节点健康检查

节点健康检查是确保Kubernetes集群稳定运行的重要环节。Kubernetes通过kubelet和节点控制器来监控节点状态。
  1. # 查看节点状态
  2. kubectl get nodes
  3. # 查看节点详细信息
  4. kubectl describe node <node-name>
  5. # 查看节点上的资源使用情况
  6. kubectl top node <node-name>
复制代码

节点问题检测器是一个守护程序,用于监控节点的健康状况,并以事件的形式报告问题。

部署节点问题检测器:
  1. apiVersion: v1
  2. kind: DaemonSet
  3. metadata:
  4.   name: node-problem-detector
  5.   namespace: kube-system
  6. spec:
  7.   selector:
  8.     matchLabels:
  9.       app: node-problem-detector
  10.   template:
  11.     metadata:
  12.       labels:
  13.         app: node-problem-detector
  14.     spec:
  15.       containers:
  16.       - name: node-problem-detector
  17.         image: k8s.gcr.io/node-problem-detector:v0.8.7
  18.         command:
  19.         - "/bin/node-problem-detector"
  20.         - "--logtostderr"
  21.         - "--system-log-monitors=/config/kernel-monitor.json,/config/docker-monitor.json"
  22.         volumeMounts:
  23.         - name: log
  24.           mountPath: /var/log
  25.         - name: config
  26.           mountPath: /config
  27.       volumes:
  28.       - name: log
  29.         hostPath:
  30.           path: /var/log/
  31.       - name: config
  32.         configMap:
  33.           name: node-problem-detector-config
复制代码

集群组件健康检查

集群组件的健康检查对于确保整个集群的正常运行至关重要。
  1. # 查看控制平面组件状态
  2. kubectl get componentstatuses
  3. # 检查API服务器连接
  4. kubectl cluster-info
  5. # 检查etcd健康状态
  6. kubectl get --raw='/healthz?verbose'
  7. # 检查各个命名空间中的Pod状态
  8. kubectl get pods --all-namespaces -o wide
复制代码

Kubernetes控制平面组件提供了健康检查端点,可以通过HTTP请求来检查其状态:
  1. # API服务器健康检查
  2. curl -k https://<api-server-ip>:6443/healthz
  3. # etcd健康检查
  4. curl -L http://<etcd-ip>:2379/health
  5. # 调度器健康检查
  6. curl -L http://<scheduler-ip>:10251/healthz
  7. # 控制器管理器健康检查
  8. curl -L http://<controller-manager-ip>:10252/healthz
复制代码

日志管理与分析

日志收集策略

在Kubernetes环境中,日志收集是故障排查的重要手段。由于Pod是短暂的,日志需要被持久化和集中管理。

Kubernetes默认会将容器的标准输出和错误输出保存到节点的/var/log/containers目录下。可以通过以下命令查看Pod日志:
  1. # 查看Pod日志
  2. kubectl logs <pod-name> -n <namespace>
  3. # 查看特定容器的日志
  4. kubectl logs <pod-name> -c <container-name> -n <namespace>
  5. # 查看最近几行日志
  6. kubectl logs --tail=100 <pod-name> -n <namespace>
  7. # 查看并跟踪日志输出
  8. kubectl logs -f <pod-name> -n <namespace>
  9. # 查看之前实例的日志(Pod重启后)
  10. kubectl logs --previous <pod-name> -n <namespace>
复制代码

使用DaemonSet在每个节点上部署日志收集代理是常见的做法。以下是使用Fluentd作为日志收集代理的示例:
  1. apiVersion: v1
  2. kind: ServiceAccount
  3. metadata:
  4.   name: fluentd
  5.   namespace: kube-system
  6. ---
  7. apiVersion: rbac.authorization.k8s.io/v1
  8. kind: ClusterRole
  9. metadata:
  10.   name: fluentd
  11. rules:
  12. - apiGroups: [""]
  13.   resources:
  14.   - namespaces
  15.   - pods
  16.   verbs: ["get", "list", "watch"]
  17. ---
  18. apiVersion: rbac.authorization.k8s.io/v1
  19. kind: ClusterRoleBinding
  20. metadata:
  21.   name: fluentd
  22. roleRef:
  23.   kind: ClusterRole
  24.   name: fluentd
  25.   apiGroup: rbac.authorization.k8s.io
  26. subjects:
  27. - kind: ServiceAccount
  28.   name: fluentd
  29.   namespace: kube-system
  30. ---
  31. apiVersion: apps/v1
  32. kind: DaemonSet
  33. metadata:
  34.   name: fluentd
  35.   namespace: kube-system
  36.   labels:
  37.     k8s-app: fluentd-logging
  38.     version: v1
  39. spec:
  40.   selector:
  41.     matchLabels:
  42.       k8s-app: fluentd-logging
  43.   template:
  44.     metadata:
  45.       labels:
  46.         k8s-app: fluentd-logging
  47.         version: v1
  48.     spec:
  49.       serviceAccount: fluentd
  50.       tolerations:
  51.       - key: node-role.kubernetes.io/master
  52.         effect: NoSchedule
  53.       containers:
  54.       - name: fluentd
  55.         image: fluent/fluentd-kubernetes-daemonset:v1-debian-elasticsearch
  56.         env:
  57.           - name:  FLUENT_ELASTICSEARCH_HOST
  58.             value: "elasticsearch-logging"
  59.           - name:  FLUENT_ELASTICSEARCH_PORT
  60.             value: "9200"
  61.           - name: FLUENT_ELASTICSEARCH_SCHEME
  62.             value: "http"
  63.           - name: FLUENTD_SYSTEMD_CONF
  64.             value: "disable"
  65.         resources:
  66.           limits:
  67.             memory: 512Mi
  68.           requests:
  69.             cpu: 100m
  70.             memory: 200Mi
  71.         volumeMounts:
  72.         - name: varlog
  73.           mountPath: /var/log
  74.         - name: varlibdockercontainers
  75.           mountPath: /var/lib/docker/containers
  76.           readOnly: true
  77.       terminationGracePeriodSeconds: 30
  78.       volumes:
  79.       - name: varlog
  80.         hostPath:
  81.           path: /var/log
  82.       - name: varlibdockercontainers
  83.         hostPath:
  84.           path: /var/lib/docker/containers
复制代码

日志分析工具

EFK(Elasticsearch + Fluentd + Kibana)是Kubernetes环境中常用的日志分析解决方案。

部署Elasticsearch:
  1. apiVersion: apps/v1
  2. kind: StatefulSet
  3. metadata:
  4.   name: elasticsearch
  5.   namespace: kube-system
  6. spec:
  7.   serviceName: elasticsearch
  8.   replicas: 1
  9.   selector:
  10.     matchLabels:
  11.       app: elasticsearch
  12.   template:
  13.     metadata:
  14.       labels:
  15.         app: elasticsearch
  16.     spec:
  17.       containers:
  18.       - name: elasticsearch
  19.         image: docker.elastic.co/elasticsearch/elasticsearch:7.10.1
  20.         ports:
  21.         - containerPort: 9200
  22.           name: http
  23.           protocol: TCP
  24.         - containerPort: 9300
  25.           name: transport
  26.           protocol: TCP
  27.         env:
  28.           - name: discovery.type
  29.             value: single-node
  30.         resources:
  31.           limits:
  32.             cpu: 1000m
  33.             memory: 2Gi
  34.           requests:
  35.             cpu: 100m
  36.             memory: 1Gi
  37.         volumeMounts:
  38.         - name: data
  39.           mountPath: /usr/share/elasticsearch/data
  40.   volumeClaimTemplates:
  41.   - metadata:
  42.       name: data
  43.     spec:
  44.       accessModes: [ "ReadWriteOnce" ]
  45.       resources:
  46.         requests:
  47.           storage: 10Gi
  48. ---
  49. apiVersion: v1
  50. kind: Service
  51. metadata:
  52.   name: elasticsearch
  53.   namespace: kube-system
  54. spec:
  55.   ports:
  56.   - port: 9200
  57.     name: http
  58.   selector:
  59.     app: elasticsearch
复制代码

部署Kibana:
  1. apiVersion: apps/v1
  2. kind: Deployment
  3. metadata:
  4.   name: kibana
  5.   namespace: kube-system
  6. spec:
  7.   replicas: 1
  8.   selector:
  9.     matchLabels:
  10.       app: kibana
  11.   template:
  12.     metadata:
  13.       labels:
  14.         app: kibana
  15.     spec:
  16.       containers:
  17.       - name: kibana
  18.         image: docker.elastic.co/kibana/kibana:7.10.1
  19.         ports:
  20.         - containerPort: 5601
  21.         env:
  22.           - name: ELASTICSEARCH_HOSTS
  23.             value: http://elasticsearch:9200
  24.         resources:
  25.           limits:
  26.             cpu: 1000m
  27.             memory: 1Gi
  28.           requests:
  29.             cpu: 100m
  30.             memory: 512Mi
  31. ---
  32. apiVersion: v1
  33. kind: Service
  34. metadata:
  35.   name: kibana
  36.   namespace: kube-system
  37. spec:
  38.   ports:
  39.   - port: 5601
  40.     protocol: TCP
  41.     targetPort: 5601
  42.   selector:
  43.     app: kibana
  44.   type: LoadBalancer
复制代码

Loki是一个受Prometheus启发的日志聚合系统,与Grafana集成良好,提供了轻量级的日志解决方案。

部署Loki:
  1. apiVersion: v1
  2. kind: ConfigMap
  3. metadata:
  4.   name: loki-config
  5.   namespace: monitoring
  6. data:
  7.   loki.yaml: |
  8.     auth_enabled: false
  9.     server:
  10.       http_listen_port: 3100
  11.     ingester:
  12.       lifecycler:
  13.         ring:
  14.           kvstore:
  15.             store: inmemory
  16.           replication_factor: 1
  17.     schema_config:
  18.       configs:
  19.         - from: 2020-10-24
  20.           store: boltdb-shipper
  21.           object_store: filesystem
  22.           schema: v11
  23.           index:
  24.             prefix: index_
  25.             period: 24h
  26.     storage_config:
  27.       boltdb_shipper:
  28.         active_index_directory: /data/loki/index
  29.         cache_location: /data/loki/cache
  30.         cache_ttl: 24h
  31.         shared_store: filesystem
  32.       filesystem:
  33.         directory: /data/loki/chunks
  34.     limits_config:
  35.       enforce_metric_name: false
  36.       reject_old_samples: true
  37.       reject_old_samples_max_age: 168h
  38.     chunk_store_config:
  39.       max_look_back_period: 0s
  40.     table_manager:
  41.       retention_deletes_enabled: false
  42.       retention_period: 0s
  43.     compactor:
  44.       working_directory: /data/loki/compactor
  45.       shared_store: filesystem
  46. ---
  47. apiVersion: apps/v1
  48. kind: StatefulSet
  49. metadata:
  50.   name: loki
  51.   namespace: monitoring
  52. spec:
  53.   replicas: 1
  54.   selector:
  55.     matchLabels:
  56.       app: loki
  57.   template:
  58.     metadata:
  59.       labels:
  60.         app: loki
  61.     spec:
  62.       containers:
  63.       - name: loki
  64.         image: grafana/loki:2.4.0
  65.         args:
  66.         - -config.file=/etc/loki/loki.yaml
  67.         ports:
  68.         - containerPort: 3100
  69.           name: http
  70.         volumeMounts:
  71.         - name: config
  72.           mountPath: /etc/loki
  73.         - name: storage
  74.           mountPath: /data
  75.       volumes:
  76.       - name: config
  77.         configMap:
  78.           name: loki-config
  79.   volumeClaimTemplates:
  80.   - metadata:
  81.       name: storage
  82.     spec:
  83.       accessModes: [ "ReadWriteOnce" ]
  84.       resources:
  85.         requests:
  86.           storage: 10Gi
  87. ---
  88. apiVersion: v1
  89. kind: Service
  90. metadata:
  91.   name: loki
  92.   namespace: monitoring
  93. spec:
  94.   ports:
  95.   - port: 3100
  96.     name: http
  97.   selector:
  98.     app: loki
复制代码

部署Promtail(日志收集代理):
  1. apiVersion: v1
  2. kind: ConfigMap
  3. metadata:
  4.   name: promtail-config
  5.   namespace: monitoring
  6. data:
  7.   promtail.yaml: |
  8.     server:
  9.       http_listen_port: 9080
  10.       grpc_listen_port: 0
  11.     positions:
  12.       filename: /tmp/positions.yaml
  13.     clients:
  14.       - url: http://loki:3100/loki/api/v1/push
  15.     scrape_configs:
  16.     - job_name: kubernetes-pods
  17.       kubernetes_sd_configs:
  18.       - role: pod
  19.       pipeline_stages:
  20.       - docker: {}
  21.       relabel_configs:
  22.       - source_labels:
  23.         - __meta_kubernetes_pod_label_app
  24.         target_label: app
  25.       - source_labels:
  26.         - __meta_kubernetes_pod_node_name
  27.         target_label: node
  28.       - source_labels:
  29.         - __meta_kubernetes_namespace
  30.         target_label: namespace
  31.       - source_labels:
  32.         - __meta_kubernetes_pod_name
  33.         target_label: pod
  34.       - source_labels:
  35.         - __meta_kubernetes_pod_container_name
  36.         target_label: container
  37.       - source_labels:
  38.         - __meta_kubernetes_pod_label_app_kubernetes_io_component
  39.         target_label: component
  40. ---
  41. apiVersion: apps/v1
  42. kind: DaemonSet
  43. metadata:
  44.   name: promtail
  45.   namespace: monitoring
  46. spec:
  47.   selector:
  48.     matchLabels:
  49.       app: promtail
  50.   template:
  51.     metadata:
  52.       labels:
  53.         app: promtail
  54.     spec:
  55.       serviceAccount: promtail
  56.       containers:
  57.       - name: promtail
  58.         image: grafana/promtail:2.4.0
  59.         args:
  60.         - -config.file=/etc/promtail/promtail.yaml
  61.         ports:
  62.         - containerPort: 9080
  63.           name: http
  64.         volumeMounts:
  65.         - name: config
  66.           mountPath: /etc/promtail
  67.         - name: containers
  68.           mountPath: /var/lib/docker/containers
  69.           readOnly: true
  70.         - name: pods
  71.           mountPath: /var/log/pods
  72.           readOnly: true
  73.       volumes:
  74.       - name: config
  75.         configMap:
  76.           name: promtail-config
  77.       - name: containers
  78.         hostPath:
  79.           path: /var/lib/docker/containers
  80.       - name: pods
  81.         hostPath:
  82.           path: /var/log/pods
复制代码

故障诊断与排查

常见故障类型

Kubernetes集群中常见的故障类型包括:

节点故障可能由硬件问题、系统崩溃或网络问题引起。表现为节点状态为NotReady。

排查步骤:
  1. # 检查节点状态
  2. kubectl get nodes
  3. # 查看节点详细信息
  4. kubectl describe node <node-name>
  5. # 检查节点上的kubelet日志
  6. ssh <node-name> 'journalctl -u kubelet -f'
  7. # 检查节点资源使用情况
  8. kubectl top node <node-name>
复制代码

Pod故障可能由资源不足、镜像问题、配置错误等引起。表现为Pod状态为Pending、CrashLoopBackOff或Error。

排查步骤:
  1. # 检查Pod状态
  2. kubectl get pods -n <namespace>
  3. # 查看Pod详细信息
  4. kubectl describe pod <pod-name> -n <namespace>
  5. # 查看Pod日志
  6. kubectl logs <pod-name> -n <namespace>
  7. # 如果Pod重启,查看前一实例日志
  8. kubectl logs --previous <pod-name> -n <namespace>
  9. # 检查Pod事件
  10. kubectl get events -n <namespace> --field-selector involvedObject.name=<pod-name>
复制代码

网络故障可能导致Pod间通信失败、服务不可访问等问题。

排查步骤:
  1. # 检查Pod IP
  2. kubectl get pods -n <namespace> -o wide
  3. # 检查服务状态
  4. kubectl get svc -n <namespace>
  5. # 检查端点状态
  6. kubectl get endpoints -n <namespace>
  7. # 进入Pod测试网络连接
  8. kubectl exec -it <pod-name> -n <namespace> -- /bin/bash
  9. # 在Pod内执行
  10. ping <target-ip>
  11. nslookup <service-name>
  12. curl <service-url>
  13. # 检查网络插件状态
  14. kubectl get pods -n kube-system | grep -E 'calico|flannel|weave|cilium'
复制代码

存储故障可能导致PVC无法绑定、Pod无法挂载卷等问题。

排查步骤:
  1. # 检查PVC状态
  2. kubectl get pvc -n <namespace>
  3. # 检查PV状态
  4. kubectl get pv
  5. # 查看PVC详细信息
  6. kubectl describe pvc <pvc-name> -n <namespace>
  7. # 检查存储类
  8. kubectl get storageclass
  9. # 检查存储提供者状态
  10. kubectl get pods -n kube-system | grep -E 'csi|provisioner'
复制代码

故障排查流程

一个系统化的故障排查流程可以帮助快速定位和解决问题。

首先确定问题是影响整个集群、单个节点还是特定应用。
  1. # 检查集群整体状态
  2. kubectl cluster-info
  3. # 检查节点状态
  4. kubectl get nodes
  5. # 检查核心组件状态
  6. kubectl get pods -n kube-system
复制代码

收集与问题相关的日志、事件和指标。
  1. # 查看集群事件
  2. kubectl get events --all-namespaces --sort-by='.metadata.creationTimestamp'
  3. # 查看资源使用情况
  4. kubectl top nodes
  5. kubectl top pods --all-namespaces
  6. # 收集节点信息
  7. kubectl get nodes -o wide
复制代码

根据收集的信息分析可能的原因。
  1. # 检查Pod状态
  2. kubectl get pods --all-namespaces -o wide
  3. # 检查未调度的Pod
  4. kubectl get pods --all-namespaces --field-selector spec.nodeName=
  5. # 检查失败的Pod
  6. kubectl get pods --all-namespaces --field-selector status.phase=Failed
复制代码

根据分析结果实施相应的解决方案。
  1. # 重启Pod
  2. kubectl delete pod <pod-name> -n <namespace>
  3. # 扩容Deployment
  4. kubectl scale deployment <deployment-name> --replicas=<new-replica-count> -n <namespace>
  5. # 排空节点
  6. kubectl cordon <node-name>
  7. kubectl drain <node-name> --ignore-daemonsets --delete-local-data
复制代码

验证问题是否已解决。
  1. # 检查Pod状态
  2. kubectl get pods -n <namespace>
  3. # 检查服务可用性
  4. kubectl get svc -n <namespace>
  5. curl <service-url>
  6. # 检查应用日志
  7. kubectl logs <pod-name> -n <namespace>
复制代码

实用排查命令和工具
  1. # 查看集群信息
  2. kubectl cluster-info
  3. # 查看资源详细信息
  4. kubectl describe <resource-type> <resource-name>
  5. # 查看资源YAML配置
  6. kubectl get <resource-type> <resource-name> -o yaml
  7. # 查看资源标签
  8. kubectl get <resource-type> --show-labels
  9. # 根据标签选择资源
  10. kubectl get <resource-type> -l <label-key>=<label-value>
  11. # 查看资源注解
  12. kubectl get <resource-type> <resource-name> -o jsonpath='{.metadata.annotations}'
  13. # 查看Pod容器镜像
  14. kubectl get pods <pod-name> -n <namespace> -o jsonpath='{.spec.containers[*].image}{"\n"}'
  15. # 查看Pod资源请求和限制
  16. kubectl get pods <pod-name> -n <namespace> -o jsonpath='{.spec.containers[*].resources}{"\n"}'
复制代码
  1. # 创建调试Pod
  2. kubectl run debug-pod --image=busybox -- sleep 3600
  3. # 进入Pod
  4. kubectl exec -it debug-pod -- /bin/sh
  5. # 在Pod内安装网络工具
  6. # 在Pod内执行
  7. apt-get update && apt-get install -y iputils-ping dnsutils curl telnet
  8. # 测试DNS解析
  9. nslookup kubernetes.default
  10. nslookup <service-name>.<namespace>.svc.cluster.local
  11. # 测试网络连接
  12. ping <target-ip>
  13. curl <target-url>
  14. telnet <target-host> <target-port>
  15. # 检查路由表
  16. ip route
复制代码
  1. # 查看节点资源分配
  2. kubectl describe nodes | grep -i "allocated resources"
  3. # 查看命名空间资源使用情况
  4. kubectl describe quota -n <namespace>
  5. # 查看资源限制范围
  6. kubectl get limitrange -n <namespace>
  7. # 查看Pod资源使用历史(需要Metrics Server)
  8. kubectl top pods --all-namespaces --sort-by=cpu
  9. kubectl top pods --all-namespaces --sort-by=memory
复制代码

自动化运维与告警

告警策略设计

有效的告警策略可以帮助运维人员及时发现并处理问题,避免小问题演变成大故障。

建议设计以下告警级别:

1. 紧急(Critical):影响核心业务,需要立即处理核心服务不可用数据丢失风险安全漏洞
2. 核心服务不可用
3. 数据丢失风险
4. 安全漏洞
5. 高(High):影响业务功能,需要尽快处理非核心服务不可用性能严重下降资源即将耗尽
6. 非核心服务不可用
7. 性能严重下降
8. 资源即将耗尽
9. 中(Medium):潜在风险,需要关注资源使用率过高错误率增加备份失败
10. 资源使用率过高
11. 错误率增加
12. 备份失败
13. 低(Low):信息性告警,需要记录配置变更计划内维护性能轻微下降
14. 配置变更
15. 计划内维护
16. 性能轻微下降

紧急(Critical):影响核心业务,需要立即处理

• 核心服务不可用
• 数据丢失风险
• 安全漏洞

高(High):影响业务功能,需要尽快处理

• 非核心服务不可用
• 性能严重下降
• 资源即将耗尽

中(Medium):潜在风险,需要关注

• 资源使用率过高
• 错误率增加
• 备份失败

低(Low):信息性告警,需要记录

• 配置变更
• 计划内维护
• 性能轻微下降

使用Prometheus配置告警规则的示例:
  1. groups:
  2. - name: kubernetes-apps
  3.   rules:
  4.   - alert: PodCrashLooping
  5.     expr: kube_pod_container_status_restarts_total > 2
  6.     for: 15m
  7.     labels:
  8.       severity: critical
  9.     annotations:
  10.       summary: "Pod {{ $labels.pod }} is crash looping (namespace {{ $labels.namespace }})"
  11.       description: "Pod {{ $labels.pod }} (namespace {{ $labels.namespace }}) has restarted {{ $value }} times in the last 15 minutes."
  12.   - alert: PodNotReady
  13.     expr: sum by (namespace, pod) (kube_pod_status_ready{condition="false"}) == 1
  14.     for: 10m
  15.     labels:
  16.       severity: high
  17.     annotations:
  18.       summary: "Pod {{ $labels.pod }} is not ready (namespace {{ $labels.namespace }})"
  19.       description: "Pod {{ $labels.pod }} (namespace {{ $labels.namespace }}) has been in a non-ready state for more than 10 minutes."
  20. - name: kubernetes-resources
  21.   rules:
  22.   - alert: NodeMemoryUsage
  23.     expr: (1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100 > 85
  24.     for: 5m
  25.     labels:
  26.       severity: high
  27.     annotations:
  28.       summary: "Node memory usage is high (instance {{ $labels.instance }})"
  29.       description: "Node memory usage is above 85% (current value: {{ $value }}%)"
  30.   - alert: NodeDiskUsage
  31.     expr: (1 - (node_filesystem_avail_bytes / node_filesystem_size_bytes)) * 100 > 85
  32.     for: 5m
  33.     labels:
  34.       severity: high
  35.     annotations:
  36.       summary: "Node disk usage is high (instance {{ $labels.instance }})"
  37.       description: "Node disk usage is above 85% (current value: {{ $value }}%)"
复制代码

自动化恢复机制

自动化恢复可以减少人工干预,提高问题解决速度。

Kubernetes默认提供了Pod自动重启机制,可以通过配置重启策略来控制:
  1. apiVersion: v1
  2. kind: Pod
  3. metadata:
  4.   name: restart-pod
  5. spec:
  6.   restartPolicy: OnFailure  # 可选值:Always、OnFailure、Never
  7.   containers:
  8.   - name: restart-container
  9.     image: busybox
  10.     command: ["sh", "-c", "exit 1"]
复制代码

HPA可以根据CPU使用率或其他指标自动调整Deployment的副本数量:
  1. apiVersion: autoscaling/v2beta2
  2. kind: HorizontalPodAutoscaler
  3. metadata:
  4.   name: app-hpa
  5. spec:
  6.   scaleTargetRef:
  7.     apiVersion: apps/v1
  8.     kind: Deployment
  9.     name: app-deployment
  10.   minReplicas: 2
  11.   maxReplicas: 10
  12.   metrics:
  13.   - type: Resource
  14.     resource:
  15.       name: cpu
  16.       target:
  17.         type: Utilization
  18.         averageUtilization: 50
  19.   - type: Resource
  20.     resource:
  21.       name: memory
  22.       target:
  23.         type: Utilization
  24.         averageUtilization: 70
复制代码

VPA可以自动调整Pod的资源请求和限制:
  1. apiVersion: autoscaling.k8s.io/v1
  2. kind: VerticalPodAutoscaler
  3. metadata:
  4.   name: app-vpa
  5. spec:
  6.   targetRef:
  7.     apiVersion: "apps/v1"
  8.     kind:       Deployment
  9.     name:       app-deployment
  10.   updatePolicy:
  11.     updateMode: "Auto"
  12.   resourcePolicy:
  13.     containerPolicies:
  14.     - containerName: "*"
  15.       minAllowed:
  16.         cpu: "100m"
  17.         memory: "50Mi"
  18.       maxAllowed:
  19.         cpu: "1"
  20.         memory: "500Mi"
  21.       controlledResources: ["cpu", "memory"]
复制代码

使用Kubernetes Operator或自定义控制器可以实现更复杂的自动化恢复逻辑。以下是一个简单的自定义控制器示例,用于自动重启失败的Pod:
  1. package main
  2. import (
  3.         "context"
  4.         "fmt"
  5.         "time"
  6.         corev1 "k8s.io/api/core/v1"
  7.         metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  8.         "k8s.io/client-go/kubernetes"
  9.         "k8s.io/client-go/rest"
  10. )
  11. func main() {
  12.         // 创建Kubernetes客户端
  13.         config, err := rest.InClusterConfig()
  14.         if err != nil {
  15.                 panic(err.Error())
  16.         }
  17.         clientset, err := kubernetes.NewForConfig(config)
  18.         if err != nil {
  19.                 panic(err.Error())
  20.         }
  21.         // 监控所有命名空间中的Pod
  22.         for {
  23.                 pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
  24.                 if err != nil {
  25.                         panic(err.Error())
  26.                 }
  27.                 // 检查每个Pod的状态
  28.                 for _, pod := range pods.Items {
  29.                         if pod.Status.Phase == corev1.PodFailed {
  30.                                 fmt.Printf("发现失败的Pod: %s/%s\n", pod.Namespace, pod.Name)
  31.                                
  32.                                 // 删除失败的Pod,让Deployment或StatefulSet重新创建
  33.                                 err := clientset.CoreV1().Pods(pod.Namespace).Delete(context.TODO(), pod.Name, metav1.DeleteOptions{})
  34.                                 if err != nil {
  35.                                         fmt.Printf("删除Pod失败: %v\n", err)
  36.                                 } else {
  37.                                         fmt.Printf("已删除失败的Pod: %s/%s\n", pod.Namespace, pod.Name)
  38.                                 }
  39.                         }
  40.                 }
  41.                 // 等待一段时间后再次检查
  42.                 time.Sleep(30 * time.Second)
  43.         }
  44. }
复制代码

最佳实践与案例分析

健康检查最佳实践

• 存活探针:用于检测应用是否存活,设置适当的初始延迟和检查间隔
• 就绪探针:用于检测应用是否准备好接收流量,避免过早将流量导向未就绪的Pod
• 启动探针:对于启动时间较长的应用,使用启动探针避免在应用启动期间被存活探针杀死
  1. apiVersion: apps/v1
  2. kind: Deployment
  3. metadata:
  4.   name: app-deployment
  5. spec:
  6.   replicas: 3
  7.   template:
  8.     spec:
  9.       containers:
  10.       - name: app-container
  11.         image: myapp:1.0
  12.         ports:
  13.         - containerPort: 8080
  14.         startupProbe:
  15.           httpGet:
  16.             path: /health
  17.             port: 8080
  18.           failureThreshold: 30
  19.           periodSeconds: 10
  20.         livenessProbe:
  21.           httpGet:
  22.             path: /health
  23.             port: 8080
  24.           initialDelaySeconds: 60
  25.           periodSeconds: 10
  26.         readinessProbe:
  27.           httpGet:
  28.             path: /ready
  29.             port: 8080
  30.           initialDelaySeconds: 5
  31.           periodSeconds: 5
复制代码

• 监控集群基础设施(节点、网络、存储)
• 监控Kubernetes组件(API服务器、调度器、控制器管理器等)
• 监控应用性能和可用性
• 设置合理的告警阈值和通知策略
  1. # Prometheus监控配置示例
  2. apiVersion: v1
  3. kind: ConfigMap
  4. metadata:
  5.   name: prometheus-config
  6. data:
  7.   prometheus.yml: |
  8.     global:
  9.       scrape_interval: 15s
  10.       evaluation_interval: 15s
  11.    
  12.     scrape_configs:
  13.     - job_name: 'kubernetes-apiservers'
  14.       kubernetes_sd_configs:
  15.       - role: endpoints
  16.       scheme: https
  17.       tls_config:
  18.         ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
  19.       bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
  20.       relabel_configs:
  21.       - source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
  22.         action: keep
  23.         regex: default;kubernetes;https
  24.    
  25.     - job_name: 'kubernetes-nodes'
  26.       kubernetes_sd_configs:
  27.       - role: node
  28.       scheme: https
  29.       tls_config:
  30.         ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
  31.       bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
  32.       relabel_configs:
  33.       - action: labelmap
  34.         regex: __meta_kubernetes_node_label_(.+)
  35.       - target_label: __address__
  36.         replacement: kubernetes.default.svc:443
  37.       - source_labels: [__meta_kubernetes_node_name]
  38.         regex: (.+)
  39.         target_label: __metrics_path__
  40.         replacement: /api/v1/nodes/${1}/proxy/metrics
  41.    
  42.     - job_name: 'kubernetes-pods'
  43.       kubernetes_sd_configs:
  44.       - role: pod
  45.       relabel_configs:
  46.       - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_scrape]
  47.         action: keep
  48.         regex: true
  49.       - source_labels: [__meta_kubernetes_pod_annotation_prometheus_io_path]
  50.         action: replace
  51.         target_label: __metrics_path__
  52.         regex: (.+)
  53.       - source_labels: [__address__, __meta_kubernetes_pod_annotation_prometheus_io_port]
  54.         action: replace
  55.         regex: ([^:]+)(?::\d+)?;(\d+)
  56.         replacement: $1:$2
  57.         target_label: __address__
  58.       - action: labelmap
  59.         regex: __meta_kubernetes_pod_label_(.+)
  60.       - source_labels: [__meta_kubernetes_namespace]
  61.         action: replace
  62.         target_label: kubernetes_namespace
  63.       - source_labels: [__meta_kubernetes_pod_name]
  64.         action: replace
  65.         target_label: kubernetes_pod_name
复制代码

• 集中收集所有组件和应用的日志
• 使用结构化日志格式,便于查询和分析
• 设置日志保留策略,平衡存储成本和查询需求
• 实现日志告警,及时发现异常模式
  1. # Fluentd日志收集配置示例
  2. apiVersion: v1
  3. kind: ConfigMap
  4. metadata:
  5.   name: fluentd-config
  6. data:
  7.   fluent.conf: |
  8.     <source>
  9.       @type tail
  10.       path /var/log/containers/*_{{.Release.Namespace}}_{{.Chart.Name}}-*.log
  11.       pos_file /var/log/fluentd-containers.log.pos
  12.       tag kubernetes.*
  13.       format json
  14.       time_format %Y-%m-%dT%H:%M:%S.%NZ
  15.     </source>
  16.     <filter kubernetes.**>
  17.       @type kubernetes_metadata
  18.     </filter>
  19.     <match kubernetes.**>
  20.       @type elasticsearch
  21.       host elasticsearch-logging
  22.       port 9200
  23.       index_name fluentd
  24.       type_name _doc
  25.     </match>
复制代码

• 使用自动扩缩容应对负载变化
• 配置自动故障恢复机制
• 实现自动化部署和回滚
• 建立自愈系统,减少人工干预
  1. # 自动扩缩容配置示例
  2. apiVersion: autoscaling/v2beta2
  3. kind: HorizontalPodAutoscaler
  4. metadata:
  5.   name: app-hpa
  6. spec:
  7.   scaleTargetRef:
  8.     apiVersion: apps/v1
  9.     kind: Deployment
  10.     name: app-deployment
  11.   minReplicas: 2
  12.   maxReplicas: 10
  13.   metrics:
  14.   - type: Resource
  15.     resource:
  16.       name: cpu
  17.       target:
  18.         type: Utilization
  19.         averageUtilization: 50
  20.   behavior:
  21.     scaleDown:
  22.       stabilizationWindowSeconds: 300
  23.       policies:
  24.       - type: Percent
  25.         value: 10
  26.         periodSeconds: 60
  27.     scaleUp:
  28.       stabilizationWindowSeconds: 60
  29.       policies:
  30.       - type: Percent
  31.         value: 100
  32.         periodSeconds: 60
  33.       - type: Pods
  34.         value: 2
  35.         periodSeconds: 60
  36.       selectPolicy: Max
复制代码

真实故障案例分析

问题描述:集群中的多个Pod一直处于Pending状态,无法调度到任何节点。

排查过程:

1. 检查Pod状态:
  1. kubectl get pods --all-namespaces | grep Pending
复制代码

1. 查看Pod详细信息,发现事件中显示”0/3 nodes are available: 3 Insufficient cpu”或”3 Insufficient memory”。
2. 检查节点资源使用情况:

查看Pod详细信息,发现事件中显示”0/3 nodes are available: 3 Insufficient cpu”或”3 Insufficient memory”。

检查节点资源使用情况:
  1. kubectl top nodes
  2. kubectl describe nodes | grep -A 5 "Allocated resources"
复制代码

1. 发现节点CPU和内存使用率均超过90%,剩余资源不足以调度新的Pod。

解决方案:

1. 短期解决方案:手动扩容节点或删除不必要的Pod释放资源。
  1. # 删除测试或非关键Pod
  2. kubectl delete pod <pod-name> -n <namespace>
  3. # 手动扩容节点(如果使用云服务)
  4. # 例如,在AWS上增加节点组大小
  5. aws autoscaling set-desired-capacity --auto-scaling-group-name <asg-name> --desired-capacity <new-size>
复制代码

1. 长期解决方案:配置集群自动扩缩容(Cluster Autoscaler)设置资源请求和限制,避免资源浪费实施Pod优先级和抢占机制,确保关键应用优先获得资源
2. 配置集群自动扩缩容(Cluster Autoscaler)
3. 设置资源请求和限制,避免资源浪费
4. 实施Pod优先级和抢占机制,确保关键应用优先获得资源

• 配置集群自动扩缩容(Cluster Autoscaler)
• 设置资源请求和限制,避免资源浪费
• 实施Pod优先级和抢占机制,确保关键应用优先获得资源
  1. # 集群自动扩缩容配置示例
  2. apiVersion: v1
  3. kind: ServiceAccount
  4. metadata:
  5.   name: cluster-autoscaler
  6.   namespace: kube-system
  7. ---
  8. apiVersion: rbac.authorization.k8s.io/v1
  9. kind: ClusterRole
  10. metadata:
  11.   name: cluster-autoscaler
  12. rules:
  13. - apiGroups: [""]
  14.   resources: ["events", "endpoints"]
  15.   verbs: ["create", "patch"]
  16. - apiGroups: [""]
  17.   resources: ["pods/eviction"]
  18.   verbs: ["create"]
  19. - apiGroups: [""]
  20.   resources: ["pods/status"]
  21.   verbs: ["update"]
  22. - apiGroups: [""]
  23.   resources: ["nodes"]
  24.   verbs: ["watch", "list", "get", "update"]
  25. - apiGroups: [""]
  26.   resources: ["namespaces"]
  27.   verbs: ["watch", "list", "get"]
  28. - apiGroups: ["coordination.k8s.io"]
  29.   resources: ["leases"]
  30.   verbs: ["create"]
  31. - apiGroups: ["coordination.k8s.io"]
  32.   resources: ["leases"]
  33.   resourceNames: ["cluster-autoscaler"]
  34.   verbs: ["get", "update"]
  35. ---
  36. apiVersion: rbac.authorization.k8s.io/v1
  37. kind: Role
  38. metadata:
  39.   name: cluster-autoscaler
  40.   namespace: kube-system
  41. rules:
  42. - apiGroups: [""]
  43.   resources: ["configmaps"]
  44.   verbs: ["create","list","watch"]
  45. - apiGroups: [""]
  46.   resources: ["configmaps"]
  47.   resourceNames: ["cluster-autoscaler-status"]
  48.   verbs: ["delete","get","update","watch"]
  49. ---
  50. apiVersion: rbac.authorization.k8s.io/v1
  51. kind: ClusterRoleBinding
  52. metadata:
  53.   name: cluster-autoscaler
  54. roleRef:
  55.   apiGroup: rbac.authorization.k8s.io
  56.   kind: ClusterRole
  57.   name: cluster-autoscaler
  58. subjects:
  59. - kind: ServiceAccount
  60.   name: cluster-autoscaler
  61.   namespace: kube-system
  62. ---
  63. apiVersion: rbac.authorization.k8s.io/v1
  64. kind: RoleBinding
  65. metadata:
  66.   name: cluster-autoscaler
  67.   namespace: kube-system
  68. roleRef:
  69.   apiGroup: rbac.authorization.k8s.io
  70.   kind: Role
  71.   name: cluster-autoscaler
  72. subjects:
  73. - kind: ServiceAccount
  74.   name: cluster-autoscaler
  75.   namespace: kube-system
  76. ---
  77. apiVersion: apps/v1
  78. kind: Deployment
  79. metadata:
  80.   name: cluster-autoscaler
  81.   namespace: kube-system
  82. spec:
  83.   replicas: 1
  84.   selector:
  85.     matchLabels:
  86.       app: cluster-autoscaler
  87.   template:
  88.     metadata:
  89.       labels:
  90.         app: cluster-autoscaler
  91.     spec:
  92.       serviceAccountName: cluster-autoscaler
  93.       containers:
  94.       - image: k8s.gcr.io/autoscaling/cluster-autoscaler:v1.22.0
  95.         name: cluster-autoscaler
  96.         resources:
  97.           limits:
  98.             cpu: 100m
  99.             memory: 300Mi
  100.           requests:
  101.             cpu: 100m
  102.             memory: 300Mi
  103.         command:
  104.         - ./cluster-autoscaler
  105.         - --balance-similar-node-groups
  106.         - --expander=priority
  107.         - --skip-nodes-with-system-pods=false
  108.         - --cloud-provider=aws
  109.         - --nodes=<min-nodes>:<max-nodes>:<node-group-name>
复制代码

问题描述:Kubernetes API服务器响应时间显著增加,kubectl命令执行缓慢,Pod创建和更新操作超时。

排查过程:

1. 检查API服务器状态:
  1. kubectl get componentstatuses
复制代码

1. 检查API服务器日志:
  1. kubectl logs -n kube-system <kube-apiserver-pod-name>
复制代码

1. 检查etcd集群状态:
  1. kubectl get pods -n kube-system | grep etcd
  2. kubectl exec -it <etcd-pod-name> -n kube-system -- etcdctl --endpoints=https://[127.0.0.1]:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key endpoint health
复制代码

1. 发现etcd集群响应时间过长,部分请求超时。
2. 检查etcd性能指标:

发现etcd集群响应时间过长,部分请求超时。

检查etcd性能指标:
  1. kubectl exec -it <etcd-pod-name> -n kube-system -- etcdctl --endpoints=https://[127.0.0.1]:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key endpoint status --write-out=table
复制代码

1. 发现etcd数据库大小过大,导致性能下降。

解决方案:

1. 短期解决方案:压缩etcd历史数据,减少数据库大小。
  1. # 在etcd节点上执行
  2. ETCDCTL_API=3 etcdctl --endpoints=https://[127.0.0.1]:2379 --cacert=/etc/kubernetes/pki/etcd/ca.crt --cert=/etc/kubernetes/pki/etcd/server.crt --key=/etc/kubernetes/pki/etcd/server.key defrag
复制代码

1. 长期解决方案:增加etcd节点资源(CPU、内存、磁盘)优化etcd配置,调整心跳间隔和选举超时实施etcd监控和告警,提前发现性能问题定期备份和压缩etcd数据
2. 增加etcd节点资源(CPU、内存、磁盘)
3. 优化etcd配置,调整心跳间隔和选举超时
4. 实施etcd监控和告警,提前发现性能问题
5. 定期备份和压缩etcd数据

• 增加etcd节点资源(CPU、内存、磁盘)
• 优化etcd配置,调整心跳间隔和选举超时
• 实施etcd监控和告警,提前发现性能问题
• 定期备份和压缩etcd数据
  1. # etcd优化配置示例
  2. apiVersion: v1
  3. kind: Pod
  4. metadata:
  5.   name: etcd
  6.   namespace: kube-system
  7. spec:
  8.   containers:
  9.   - name: etcd
  10.     image: k8s.gcr.io/etcd:3.4.13-0
  11.     command:
  12.     - etcd
  13.     - --name=etcd-0
  14.     - --data-dir=/var/lib/etcd
  15.     - --listen-client-urls=https://0.0.0.0:2379
  16.     - --advertise-client-urls=https://<node-ip>:2379
  17.     - --listen-peer-urls=https://0.0.0.0:2380
  18.     - --initial-advertise-peer-urls=https://<node-ip>:2380
  19.     - --initial-cluster=etcd-0=https://<node-ip>:2380
  20.     - --initial-cluster-token=my-etcd-token
  21.     - --initial-cluster-state=new
  22.     - --client-cert-auth=true
  23.     - --trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
  24.     - --cert-file=/etc/kubernetes/pki/etcd/server.crt
  25.     - --key-file=/etc/kubernetes/pki/etcd/server.key
  26.     - --peer-client-cert-auth=true
  27.     - --peer-trusted-ca-file=/etc/kubernetes/pki/etcd/ca.crt
  28.     - --peer-cert-file=/etc/kubernetes/pki/etcd/peer.crt
  29.     - --peer-key-file=/etc/kubernetes/pki/etcd/peer.key
  30.     # 优化参数
  31.     - --heartbeat-interval=300
  32.     - --election-timeout=2000
  33.     - --max-snapshots=5
  34.     - --max-wals=5
  35.     - --quota-backend-bytes=4294967296
  36.     - --auto-compaction-retention=1
  37.     resources:
  38.       requests:
  39.         cpu: 200m
  40.         memory: 1Gi
  41.       limits:
  42.         cpu: 1000m
  43.         memory: 4Gi
  44.     volumeMounts:
  45.     - name: etcd-data
  46.       mountPath: /var/lib/etcd
  47.   volumes:
  48.   - name: etcd-data
  49.     hostPath:
  50.       path: /var/lib/etcd
  51.       type: DirectoryOrCreate
复制代码

问题描述:集群中的Pod无法相互通信,服务无法访问,应用功能异常。

排查过程:

1. 检查Pod状态和网络配置:
  1. kubectl get pods --all-namespaces -o wide
复制代码

1. 检查服务状态:
  1. kubectl get svc --all-namespaces
  2. kubectl get endpoints --all-namespaces
复制代码

1. 检查网络插件状态:
  1. kubectl get pods -n kube-system | grep -E 'calico|flannel|weave|cilium'
复制代码

1. 检查网络插件日志:
  1. kubectl logs -n kube-system <network-plugin-pod-name>
复制代码

1. 创建测试Pod进行网络连通性测试:
  1. kubectl run test-pod --image=busybox -- sleep 3600
  2. kubectl exec -it test-pod -- /bin/sh
  3. # 在Pod内执行
  4. ping <target-pod-ip>
  5. nslookup <service-name>
复制代码

1. 发现网络插件Pod异常重启,节点间网络配置不正确。

解决方案:

1. 短期解决方案:重启网络插件Pod,修复配置问题。
  1. # 重启网络插件Pod
  2. kubectl delete pod -n kube-system -l k8s-app=<network-plugin-name>
  3. # 检查网络配置
  4. # 对于Calico
  5. kubectl get ippools.crd.projectcalico.org -o yaml
  6. # 对于Flannel
  7. kubectl get configmap -n kube-system kube-flannel-cfg -o yaml
复制代码

1. 长期解决方案:实施网络插件监控和告警定期检查网络配置和状态准备网络插件故障的应急响应计划考虑使用多网络插件或网络策略提高可靠性
2. 实施网络插件监控和告警
3. 定期检查网络配置和状态
4. 准备网络插件故障的应急响应计划
5. 考虑使用多网络插件或网络策略提高可靠性

• 实施网络插件监控和告警
• 定期检查网络配置和状态
• 准备网络插件故障的应急响应计划
• 考虑使用多网络插件或网络策略提高可靠性
  1. # 网络插件监控配置示例
  2. apiVersion: v1
  3. kind: ConfigMap
  4. metadata:
  5.   name: network-plugin-monitoring
  6.   namespace: monitoring
  7. data:
  8.   network-rules.yml: |
  9.     groups:
  10.     - name: network-plugin
  11.       rules:
  12.       - alert: NetworkPluginPodDown
  13.         expr: up{job="network-plugin"} == 0
  14.         for: 5m
  15.         labels:
  16.           severity: critical
  17.         annotations:
  18.           summary: "Network plugin pod is down"
  19.           description: "Network plugin pod {{ $labels.pod }} has been down for more than 5 minutes."
  20.       
  21.       - alert: NetworkConnectivityFailure
  22.         expr: probe_success{job="network-connectivity"} == 0
  23.         for: 5m
  24.         labels:
  25.           severity: critical
  26.         annotations:
  27.           summary: "Network connectivity test failed"
  28.           description: "Network connectivity test between pods failed for more than 5 minutes."
复制代码

总结与展望

Kubernetes集群健康检查是确保系统高可用性的关键环节。通过本文的介绍,我们了解了从监控指标到故障维护的完整流程,包括监控工具的选择、健康检查策略的实施、日志管理与分析、故障诊断与排查、自动化运维与告警,以及最佳实践和案例分析。

有效的健康检查体系应该包括:

1. 全面的监控覆盖:从基础设施到应用层的全方位监控
2. 合理的健康检查策略:根据应用特点设计合适的探针
3. 集中的日志管理:实现日志的收集、存储、分析和告警
4. 系统化的故障排查:建立标准化的故障处理流程
5. 智能化的自动化运维:减少人工干预,提高故障恢复速度

随着云原生技术的发展,Kubernetes集群健康检查也在不断演进。未来,我们可以期待以下发展趋势:

1. AI驱动的预测性维护:利用机器学习算法分析监控数据,预测潜在问题
2. 更精细的故障定位:通过分布式追踪等技术,实现请求级别的故障定位
3. 自适应的健康检查:根据系统负载和状态动态调整检查策略
4. 跨集群的健康管理:在多云和混合云环境下实现统一的健康检查
5. 更强大的自愈能力:实现更复杂的自动化故障恢复机制

作为运维人员,我们需要不断学习和实践,构建完善的健康检查体系,确保Kubernetes集群的稳定运行,为业务提供可靠的基础设施支持。通过本文提供的方法和工具,相信大家能够更好地管理和维护Kubernetes集群,快速定位并解决问题,保障系统的高可用性。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则