Prometheus 是一个功能强大的开源监控系统,广泛用于收集和存储 Kubernetes 集群的指标。它使开发人员和操作人员能够深入了解其应用程序和基础设施的性能和健康状况。


下面的代码演示了如何使用简单的配置文件在 Kubernetes 集群中部署 Prometheus。

【代码清单】

apiVersion: v1 
kind: Service 
metadata: 
 name: prometheus 
spec: 
 ports: 
  - port: 9090 
   targetPort: 9090 
 selector: 
  app: prometheus 
--- 
apiVersion: apps/v1 
kind: Deployment 
metadata: 
 name: prometheus 
spec: 
 replicas: 1 
 selector: 
  matchLabels: 
   app: prometheus 
 template: 
  metadata: 
   labels: 
     app: prometheus 
  spec: 
   containers: 
     - name: prometheus 
      image: prom/prometheus 
      ports: 
       - containerPort: 9090 
      args: 
       - "--config.file=/etc/prometheus/prometheus.yml" 
       - "--storage.tsdb.path=/prometheus" 
       - "--web.listen-address=:9090" 
      volumeMounts: 
       - name: config-volume 
        mountPath: /etc/prometheus 
       - name: data-volume 
        mountPath: /prometheus 
   volumes: 
     - name: config-volume 
      configMap: 
       name: prometheus-config 
     - name: data-volume 
      emptyDir: {} 

【执行结果】

部署将创建一个 Prometheus 服务器,访问地址为 http://<your-kubernetes-node-ip>:9090。

此 YAML 配置为 Prometheus 定义了 Kubernetes 服务和部署。服务在端口 9090 上公开 Prometheus,而部署则管理 Prometheus 容器。应配置 prometheus.yml 文件(此处未显示),以指定要采集的指标。emptyDir 卷用于临时存储 Prometheus 数据。

【小知识】

Prometheus 采用拉动模式来收集指标,这意味着它能以指定的时间间隔从目标中获取数据。它支持多维数据收集和查询,允许用户以各种方式切分指标。此外,Prometheus 还能与 Kubernetes 无缝协作,自动发现服务和端点。