跳到主要内容

实战-prometheus部署到k8s-2022.4.29(测试成功)

最后更新于:

实战:prometheus部署到k8s-2022.4.29(测试成功)

前置条件

  • 实验环境
1k8s:v1.22.2,containerd:1.5.5
2prometheus:prom/prometheus:v2.34.0

将Prometheus应用部署在k8s里

  • 实验软件

直接拷贝文档代码即可!

链接:https://pan.baidu.com/s/12jfLts2wtJQUvT3WrD9EJg?pwd=rbvo

提取码:rbvo

2022.4.29-prometheus综合应用demo-code

1、创建monitor命名空间

  • 为了方便管理,我们将监控相关的所有资源对象都安装在monitor 这个 namespace 下面,没有的话可以提前创建。
1[root@master1 ~]#kubectl create ns monitor
2namespace/monitor created

2、创建ConfigMap资源

prometheus.yml 文件用 ConfigMap 的形式进行管理

  • 本次实验目录如下:
1[root@master1 ~]#mkdir prometheus-example
2[root@master1 ~]#cd prometheus-example/
  • 为了能够方便的管理配置文件,我们这里将 prometheus.yml 文件用 ConfigMap 的形式进行管理:

[root@master1 prometheus-example]#vim prometheus-cm.yaml

 1# prometheus-cm.yaml
 2apiVersion: v1
 3kind: ConfigMap
 4metadata:
 5  name: prometheus-config
 6  namespace: monitor
 7data:
 8  prometheus.yml: |
 9    global:
10      scrape_interval: 15s
11      scrape_timeout: 15s
12    scrape_configs:
13    - job_name: 'prometheus'
14      static_configs:
15      - targets: ['localhost:9090']

注意:

3、创建 Pod 资源

现在我们来创建 prometheus 的 Pod 资源:

[root@master1 prometheus-example]#vim prometheus-deploy.yaml

 1# prometheus-deploy.yaml
 2apiVersion: apps/v1
 3kind: Deployment
 4metadata:
 5  name: prometheus
 6  namespace: monitor
 7  labels:
 8    app: prometheus
 9spec:
10  selector:
11    matchLabels:
12      app: prometheus
13  template:
14    metadata:
15      labels:
16        app: prometheus
17    spec:
18      serviceAccountName: prometheus
19      containers:
20      - image: prom/prometheus:v2.34.0
21        name: prometheus
22        args:
23        - "--config.file=/etc/prometheus/prometheus.yml" #prometheus的配置文件
24        - "--storage.tsdb.path=/prometheus"  # 指定tsdb数据路径
25        - "--storage.tsdb.retention.time=24h" #保存时间
26        - "--web.enable-admin-api"  # 控制对admin HTTP API的访问,其中包括删除时间序列等功能
27        - "--web.enable-lifecycle"  # 支持热更新,直接执行localhost:9090/-/reload立即生效
28        ports:
29        - containerPort: 9090
30          name: http
31        volumeMounts:
32        - mountPath: "/etc/prometheus"
33          name: config-volume
34        - mountPath: "/prometheus"
35          name: data
36        resources:
37          requests:
38            cpu: 100m
39            memory: 512Mi
40          limits:
41            cpu: 100m
42            memory: 512Mi
43      volumes:
44      - name: data #tsdb数据路径:/prometheus,这里使用的是pvc
45        persistentVolumeClaim:
46          claimName: prometheus-data
47      - configMap: #
48          name: prometheus-config
49        name: config-volume

说明:

1…… #上面突然写成那种我还看不懂了哈哈……老铁,没毛病!
2      volumes: #这里要再次熟悉下关于volumes/volumeMounts数据卷挂载的使用方法!!!
3      - name: data #tsdb数据路径:/prometheus,这里使用的是pvc
4        persistentVolumeClaim:
5          claimName: prometheus-data
6      - name: config-volume
7        configMap: #
8           name: prometheus-config

另外为了 prometheus 的性能和数据持久化我们这里是直接将通过一个 LocalPV 来进行数据持久化的,通过 --storage.tsdb.path=/prometheus 指定数据目录。

4、创建pv/pvc资源

创建如下所示的一个 PVC 资源对象,注意是一个 LocalPV,和 node1 节点具有亲和性:

  • 先在宿主机node1节点上上创建这个下面LocalPV要使用到的本地目录:
1[root@master1 ~]#ssh node1
2Last login: Fri Apr 29 09:57:06 2022 from master1
3[root@node1 ~]#mkdir -p  /data/k8s/prometheus
  • 创建prometheus-pvc.yaml文件:(这里继续在master1上配置)

[root@master1 prometheus-example]#vim prometheus-pvc.yaml

 1#prometheus-pvc.yaml
 2apiVersion: v1
 3kind: PersistentVolume
 4metadata:
 5  name: prometheus-local
 6  labels:
 7    app: prometheus
 8spec:
 9  accessModes:
10  - ReadWriteOnce
11  capacity:
12    storage: 20Gi
13  storageClassName: local-storage
14  local:
15    path: /data/k8s/prometheus #一定要先在宿主机上创建这个目录!!!
16  nodeAffinity: #pv也是可以配置节点亲和性的哦!!!
17    required:
18      nodeSelectorTerms:
19      - matchExpressions:
20        - key: kubernetes.io/hostname
21          operator: In
22          values:
23          - node1 #这里是自己的node1节点
24  persistentVolumeReclaimPolicy: Retain
25---
26apiVersion: v1
27kind: PersistentVolumeClaim
28metadata:
29  name: prometheus-data
30  namespace: monitor
31spec:
32  selector:
33    matchLabels:
34      app: prometheus
35  accessModes:
36  - ReadWriteOnce
37  resources:
38    requests:
39      storage: 20Gi
40  storageClassName: local-storage

5、创建rbac资源

由于 prometheus 可以访问 Kubernetes 的一些资源对象,所以需要配置 rbac 相关认证,这里我们使用了一个名为 prometheus 的 serviceAccount 对象:

[root@master1 prometheus-example]#vim prometheus-rbac.yaml

 1# prometheus-rbac.yaml
 2apiVersion: v1
 3kind: ServiceAccount #创建一个ServiceAccount
 4metadata:
 5  name: prometheus
 6  namespace: monitor
 7---
 8apiVersion: rbac.authorization.k8s.io/v1
 9kind: ClusterRole
10metadata:
11  name: prometheus
12rules:
13- apiGroups:
14  - ""
15  resources:
16  - nodes
17  - services
18  - endpoints
19  - pods
20  - nodes/proxy
21  verbs:
22  - get
23  - list
24  - watch
25- apiGroups:
26  - "extensions"
27  resources:
28    - ingresses
29  verbs:
30  - get
31  - list
32  - watch
33- apiGroups:
34  - ""
35  resources:
36  - configmaps
37  - nodes/metrics
38  verbs:
39  - get
40- nonResourceURLs:
41  - /metrics
42  verbs:
43  - get
44---
45apiVersion: rbac.authorization.k8s.io/v1
46kind: ClusterRoleBinding
47metadata:
48  name: prometheus
49roleRef:
50  apiGroup: rbac.authorization.k8s.io
51  kind: ClusterRole
52  name: prometheus
53subjects:
54- kind: ServiceAccount
55  name: prometheus
56  namespace: monitor

由于我们要获取的资源信息,在每一个 namespace 下面都有可能存在,所以我们这里使用的是 ClusterRole 的资源对象。

值得一提的是我们这里的权限规则声明中有一个 nonResourceURLs 的属性,是用来对非资源型 metrics 进行操作的权限声明,这个在以前我们很少遇到过。

6、创建以上资源

  • 创建prometheus.yml

我们这里暂时只配置了对 prometheus本身的监控,直接创建该资源对象:

1[root@master1 prometheus-example]#kubectl apply -f prometheus-cm.yaml
2configmap/prometheus-config created

配置文件创建完成了,以后如果我们有新的资源需要被监控,我们只需要将上面的 ConfigMap 对象更新即可。

  • 创建prometheus-pv-pvc.yaml
 1[root@master1 prometheus-example]#kubectl apply -f prometheus-pvc.yaml 
 2persistentvolume/prometheus-local created
 3persistentvolumeclaim/prometheus-data created
 4
 5#验证
 6[root@master1 prometheus-example]#kubectl get pvc -nmonitor
 7NAME              STATUS   VOLUME             CAPACITY   ACCESS MODES   STORAGECLASS    AGE
 8prometheus-data   Bound    prometheus-local   20Gi       RWO            local-storage   33s
 9[root@master1 prometheus-example]#kubectl get pv
10NAME               CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                     STORAGECLASS    REASON   AGE
11prometheus-local   20Gi       RWO            Retain           Bound    monitor/prometheus-data   local-storage            35s

  • 创建prometheus-rbac.yaml
1[root@master1 prometheus-example]#kubectl apply -f prometheus-rbac.yaml
2serviceaccount "prometheus" created
3clusterrole.rbac.authorization.k8s.io "prometheus" created
4clusterrolebinding.rbac.authorization.k8s.io "prometheus" created
  • 现在我们就可以添加 promethues 的资源对象了:
 1[root@master1 prometheus-example]#kubectl apply -f prometheus-deploy.yaml 
 2deployment.apps/prometheus created
 3
 4[root@master1 prometheus-example]#kubectl get pods -n monitor
 5NAME                          READY   STATUS             RESTARTS      AGE
 6prometheus-58f59fd485-7hncv   0/1     CrashLoopBackOff   2 (24s ago)   112s
 7
 8[root@master1 prometheus-example]#kubectl logs  prometheus-58f59fd485-7hncv -nmonitor
 9ts=2022-04-29T04:42:09.982Z caller=main.go:516 level=info msg="Starting Prometheus" version="(version=2.34.0, branch=HEAD, revision=881111fec4332c33094a6fb2680c71fffc427275)"
10ts=2022-04-29T04:42:09.982Z caller=main.go:521 level=info build_context="(go=go1.17.8, user=root@121ad7ea5487, date=20220315-15:18:00)"
11ts=2022-04-29T04:42:09.982Z caller=main.go:522 level=info host_details="(Linux 3.10.0-957.el7.x86_64 #1 SMP Thu Nov 8 23:39:32 UTC 2018 x86_64 prometheus-58f59fd485-7hncv (none))"
12ts=2022-04-29T04:42:09.982Z caller=main.go:523 level=info fd_limits="(soft=65536, hard=65536)"
13ts=2022-04-29T04:42:09.982Z caller=main.go:524 level=info vm_limits="(soft=unlimited, hard=unlimited)"
14ts=2022-04-29T04:42:09.983Z caller=query_logger.go:90 level=error component=activeQueryTracker msg="Error opening query log file" file=/prometheus/queries.active err="open /prometheus/queries.active: permission denied"
15panic: Unable to create mmap-ed active query log
16
17goroutine 1 [running]:
18github.com/prometheus/prometheus/promql.NewActiveQueryTracker({0x7ffe09113e00, 0xb}, 0x14, {0x3637a40, 0xc0002032c0})
19        /app/promql/query_logger.go:120 +0x3d7
20main.main()
21        /app/cmd/prometheus/main.go:569 +0x6049

创建 Pod 后,我们可以看到并没有成功运行,出现了 open /prometheus/queries.active: permission denied 这样的错误信息,这是因为我们的 prometheus 的镜像中是使用的 nobody 这个用户,然后现在我们通过 LocalPV 挂载到宿主机上面的目录的 ownership 却是 root

1[root@node1 ~]#ls -la /data/k8s
2total 0
3drwxr-xr-x 3 root root 24 Apr 29 09:57 .
4drwxr-xr-x 3 root root 17 Apr 29 09:57 ..
5drwxr-xr-x 2 root root  6 Apr 29 09:57 prometheus

所以当然会出现操作权限问题了。

这个时候我们就可以通过 securityContext 来为 Pod 设置下 volumes 的权限,通过设置 runAsUser=0 指定运行的用户为 root;也可以通过设置一个 initContainer 来修改数据目录权限(本次使用后面这种方法):

1[root@master1 prometheus-example]#vim prometheus-deploy.yaml 
2......
3initContainers:
4- name: fix-permissions
5  image: busybox
6  command: [chown, -R, "nobody:nobody", /prometheus]
7  volumeMounts:
8  - name: data
9    mountPath: /prometheus

完整代码如下:

 1# prometheus-deploy.yaml
 2apiVersion: apps/v1
 3kind: Deployment
 4metadata:
 5  name: prometheus
 6  namespace: monitor
 7  labels:
 8    app: prometheus
 9spec:
10  selector:
11    matchLabels:
12      app: prometheus
13  template:
14    metadata:
15      labels:
16        app: prometheus
17    spec:
18      serviceAccountName: prometheus
19      initContainers:
20      - name: fix-permissions
21        image: busybox
22        command: [chown, -R, "nobody:nobody", /prometheus]
23        volumeMounts:
24        - name: data
25          mountPath: /prometheus
26      containers:
27      - image: prom/prometheus:v2.34.0
28        name: prometheus
29        args:
30        - "--config.file=/etc/prometheus/prometheus.yml"
31        - "--storage.tsdb.path=/prometheus"  # 指定tsdb数据路径
32        - "--storage.tsdb.retention.time=24h" #保存时间
33        - "--web.enable-admin-api"  # 控制对admin HTTP API的访问,其中包括删除时间序列等功能
34        - "--web.enable-lifecycle"  # 支持热更新,直接执行localhost:9090/-/reload立即生效
35        ports:
36        - containerPort: 9090
37          name: http
38        volumeMounts:
39        - mountPath: "/etc/prometheus"
40          name: config-volume
41        - mountPath: "/prometheus"
42          name: data
43        resources:
44          requests:
45            cpu: 100m
46            memory: 512Mi
47          limits:
48            cpu: 100m
49            memory: 512Mi
50      volumes: #这里要再次熟悉下关于volumes/volumeMounts数据卷挂载的使用方法!!!
51      - name: data #tsdb数据路径:/prometheus,这里使用的是pvc
52        persistentVolumeClaim:
53          claimName: prometheus-data
54      - configMap: #
55          name: prometheus-config
56        name: config-volume
  • 这个时候我们重新更新下 prometheus:
 1[root@master1 prometheus-example]#kubectl apply -f prometheus-deploy.yaml
 2deployment.apps/prometheus configured
 3#注意:这里下载镜像要耐心等待一会儿!!!74M大小!
 4
 5[root@master1 prometheus-example]#kubectl get pods -n monitor
 6NAME                          READY   STATUS    RESTARTS   AGE
 7prometheus-849c8456c7-dz6rt   1/1     Running   0          54s
 8
 9
10[root@master1 prometheus-example]#kubectl logs prometheus-849c8456c7-dz6rt  -nmonitor
11……
12ts=2022-04-29T05:00:09.184Z caller=main.go:1142 level=info msg="Loading configuration file" filename=/etc/prometheus/prometheus.yml
13ts=2022-04-29T05:00:09.185Z caller=main.go:1179 level=info msg="Completed loading of configuration file" filename=/etc/prometheus/prometheus.yml totalDuration=1.128855ms db_storage=1.302µs remote_storage=5.18µs web_handler=721ns query_engine=2.705µs scrape=773.91µs scrape_sd=66.725µs notify=1.443µs notify_sd=2.966µs rules=4.859µs tracing=20.118µs
14ts=2022-04-29T05:00:09.185Z caller=main.go:910 level=info msg="Server is ready to receive web requests."

7、创建svc资源

  • Pod 创建成功后,为了能够在外部访问到 prometheus 的 服务,我们还需要创建一个 Service 对象:

[root@master1 prometheus-example]#vim prometheus-svc.yaml

 1# prometheus-svc.yaml
 2apiVersion: v1
 3kind: Service
 4metadata:
 5  name: prometheus
 6  namespace: monitor
 7  labels:
 8    app: prometheus
 9spec:
10  selector:
11    app: prometheus
12  type: NodePort
13  ports:
14    - name: web
15      port: 9090
16      targetPort: http
  • 为了方便测试,我们这里创建一个 NodePort 类型的服务,当然我们可以创建一个 Ingress对象,通过域名来进行访问:
1[root@master1 prometheus-example]#kubectl apply -f prometheus-svc.yaml
2service/prometheus created
3
4[root@master1 prometheus-example]#kubectl get svc -nmonitor
5NAME         TYPE       CLUSTER-IP     EXTERNAL-IP   PORT(S)          AGE
6prometheus   NodePort   10.108.47.93   <none>        9090:30092/TCP   9s

8、测试

  • 现在我们就可以通过 http://任意节点IP:30980 访问 prometheus 的 webui 服务了:

  • 现在我们可以查看当前监控系统中的一些监控目标(Status -> Targets):

由于我们现在还没有配置任何的报警信息,所以 Alerts 菜单下面现在没有任何数据,隔一会儿,我们可以去 Graph 菜单下面查看我们抓取的 prometheus 本身的一些监控数据了,其中 - insert metrics at cursor -下面就有我们搜集到的一些监控指标数据:

  • 比如我们这里就选择 scrape_duration_seconds 这个指标,然后点击 Execute,就可以看到类似于下面的图表数据了:

测试结束。😘

最新文章

文档导航