K8S CPU 使用率是指 Kubernetes 集群中各个节点和 Pod 的 CPU 使用情况。监控 CPU 使用率对于优化资源分配和性能调优非常重要。在Kubernetes中,可以通过以下步骤来监控 CPU 使用率:

| 步骤 | 操作 |
|------|------|
| 1 | 安装 Heapster 或 Metrics Server |
| 2 | 部署 Prometheus 和 Grafana |
| 3 | 配置 Prometheus 采集数据 |
| 4 | 可视化数据在 Grafana 中显示 |

### 步骤一:安装 Heapster 或 Metrics Server

1. 使用 Kubernetes Dashboard 来查看当前集群是否安装 Heapster 或 Metrics Server。

```
kubectl get pods -n kube-system
```

2. 如果没有安装,可以使用 Helm 来部署 Metrics Server。

```
helm repo add stable https://kubernetes-charts.storage.googleapis.com/
helm install metrics-server stable/metrics-server
```

### 步骤二:部署 Prometheus 和 Grafana

1. 部署 Prometheus Operator。

```
kubectl create -f https://raw.githubusercontent.com/prometheus-operator/kube-prometheus/main/manifests/setup
kubectl create -f https://raw.githubusercontent.com/prometheus-operator/kube-prometheus/main/manifests
```

2. 部署 Grafana。

```
kubectl apply -f https://raw.githubusercontent.com/prometheus-operator/kube-prometheus/main/manifests/grafana
```

### 步骤三:配置 Prometheus 采集数据

1. 创建 ServiceMonitor 对象以定义要监控的目标。

```yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: cpu-usage-monitor
namespace: default
spec:
selector:
matchLabels:
app: your-app
endpoints:
- port: web
```

2. 将 ServiceMonitor 对象应用到 Prometheus。

```
kubectl apply -f servicemonitor.yaml
```

### 步骤四:可视化数据在 Grafana 中显示

1. 打开 Grafana UI,并添加 Prometheus 数据源。

2. 导入 Prometheus CPU 监控仪表盘。

```
kubectl apply -f https://raw.githubusercontent.com/coreos/kube-prometheus/main/manifests/grafana-dashboardDefinitions/k8s-cpu/cluster-cpu-resources.yaml
```

现在,你已经成功设置了监控K8S CPU使用率的整个过程。通过 Prometheus 和 Grafana,你可以实时监控集群中各个节点和 Pod 的 CPU 使用情况,从而做出更好的资源调配和优化决策。希望这篇文章对你有所帮助!