Kubernetes 在 Linux 上的监控实践
一 监控分层与组件
| 层级 | 组件 | 作用与端口/地址 |
|---|---|---|
| 基础资源 | Metrics Server | 为 HPA/VPA/Cluster Autoscaler 提供资源指标(如 CPU/内存),是 K8s 资源度量的聚合入口 |
| 节点与系统 | node_exporter(DaemonSet) | 暴露节点级指标(CPU、内存、磁盘、网络),默认端口 9100 |
| 容器与编排 | cAdvisor(已集成于 kubelet) | 收集容器资源与性能,默认 10250/10255 路径 |
| 编排状态 | kube-state-metrics | 将 Pod/Deployment/Node 等对象状态转为指标 |
| 可视化与告警 | Prometheus + Alertmanager + Grafana | 指标抓取、存储、告警与可视化 |
| 日志 | Loki 或 ELK(Elasticsearch/Logstash/Kibana) | 聚合与检索容器与节点日志 |
| 主机与内核 | Linux 工具(如 nmon) | 辅助排查节点性能与瓶颈 |
以上组件覆盖了节点、容器、编排对象与日志的全链路监控需求,适合在 CentOS/RHEL 等 Linux 发行版上落地。
二 快速上手 Prometheus + Grafana
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm install prometheus prometheus-community/kube-prometheus-stack --namespace monitoring --create-namespace
helm repo add grafana https://grafana.github.io/helm-charts
helm install grafana grafana/grafana --namespace monitoring
kubectl get secret -n monitoring grafana -o jsonpath='{.data.admin-password}' | base64 -d
kubectl port-forward -n monitoring svc/grafana 3000:80
wget https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-1.2.2.linux-amd64.tar.gz
tar -xvf node_exporter-1.2.2.linux-amd64.tar.gz && cd node_exporter-1.2.2.linux-amd64
./node_exporter
scrape_configs:
- job_name: 'node_exporter'
static_configs:
- targets: ['<node1_ip>:9100','<node2_ip>:9100']
- job_name: 'kubernetes-nodes'
scheme: https
tls_config:
ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
kubernetes_sd_configs:
- role: node
relabel_configs:
- action: labelmap
regex: __meta_kubernetes_node_label_(.+)
- target_label: __address__
replacement: kubernetes.default.svc:443
- source_labels: [__meta_kubernetes_node_name]
regex: (.+)
target_label: __metrics_path__
replacement: /api/v1/nodes/${1}/proxy/metrics
三 日志监控与可视化
helm install loki grafana/loki-stack --namespace monitoring
# Grafana 添加 Loki 数据源:http://loki.monitoring.svc.cluster.local:3100
kubectl logs <pod-name> -n <namespace>
kubectl logs -f <pod-name> -n <namespace> # 实时跟踪
kubectl get events --all-namespaces --sort-by=.metadata.creationTimestamp
四 快速排障与常用命令
kubectl get nodes
kubectl get pods --all-namespaces
kubectl get deployments --all-namespaces
kubectl get services --all-namespaces
kubectl describe pod <pod-name> -n <namespace>
kubectl describe deployment <deploy-name> -n <namespace>
kubectl get events --all-namespaces --sort-by=.metadata.creationTimestamp
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/v2.7.0/aio/deploy/recommended.yaml
kubectl proxy
# 访问:http://localhost:8001/api/v1/namespaces/kubernetes-dashboard/services/https:kubernetes-dashboard:/proxy/
# 获取 Token:kubectl -n kube-system create token admin-user
yum install -y cockpit
systemctl enable --now cockpit.socket
firewall-cmd --permanent --add-service=cockpit && firewall-cmd --reload
# 访问:http://<server_ip>:9090