4.2. 为用户定义的项目设置指标集合

您可以创建一个 ServiceMonitor 资源,从用户定义的项目中的服务端点提取指标。这假设您的应用程序使用 Prometheus 客户端库向 /metrics 规范名称公开指标。

本节介绍了如何在用户定义的项目中部署示例服务,然后创建一个 ServiceMonitor 资源来定义应该如何监控该服务。

4.2.1. 部署示例服务

要为用户定义的项目中服务测试监控,您可以部署示例服务。

流程

  1. 为服务配置创建 YAML 文件。在本例中,该文件名为 prometheus-example-app.yaml
  2. 在该文件中添加以下部署和服务配置详情:

    apiVersion: v1
    kind: Namespace
    metadata:
      name: ns1
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      labels:
        app: prometheus-example-app
      name: prometheus-example-app
      namespace: ns1
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: prometheus-example-app
      template:
        metadata:
          labels:
            app: prometheus-example-app
        spec:
          containers:
          - image: ghcr.io/rhobs/prometheus-example-app:0.3.0
            imagePullPolicy: IfNotPresent
            name: prometheus-example-app
    ---
    apiVersion: v1
    kind: Service
    metadata:
      labels:
        app: prometheus-example-app
      name: prometheus-example-app
      namespace: ns1
    spec:
      ports:
      - port: 8080
        protocol: TCP
        targetPort: 8080
        name: web
      selector:
        app: prometheus-example-app
      type: ClusterIP

    此配置会在用户定义的 ns1 项目中部署名为 prometheus-example-app 的服务。此服务会公开自定义 version 指标。

  3. 将配置应用到集群:

    $ oc apply -f prometheus-example-app.yaml

    部署该服务需要一些时间。

  4. 您可以检查该 Pod 是否正在运行:

    $ oc -n ns1 get pod

    输出示例

    NAME                                      READY     STATUS    RESTARTS   AGE
    prometheus-example-app-7857545cb7-sbgwq   1/1       Running   0          81m