Todos los productos
Search
Centro de documentos

Managed Service for Prometheus:Crear detección de servicios con un ServiceMonitor

Última actualización: Sep 30, 2026

Managed Service for Prometheus admite la detección de servicios mediante el CRD ServiceMonitor. Un ServiceMonitor define el alcance del namespace para detectar pods y selecciona los Services objetivo con matchLabel. Este tutorial usa una aplicación Spring Boot como ejemplo.

Demostración

Descargue el proyecto de demostración para consultar un ejemplo completo de detección de servicios basado en ServiceMonitor.

Paso 1: Agregar dependencias

  1. Cree una aplicación Maven y agregue a continuación las dependencias al archivo pom.xml.

        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>io.micrometer</groupId>
                <artifactId>micrometer-registry-prometheus</artifactId>
                <version>1.6.6</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <optional>true</optional>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
        </dependencies>
  2. Agregue la siguiente configuración al archivo src/resources/applications.properties del proyecto.

    management.endpoints.web.exposure.include=prometheus
  3. Inicie el proyecto y acceda a http://{host}:{port}/actuator/prometheus desde un navegador.

    Se muestran los datos de monitoreo de la JVM. A continuación se presenta un ejemplo de salida en formato de exposición de Prometheus.

    # HELP jvm_threads_daemon_threads The current number of live daemon threads
    # TYPE jvm_threads_daemon_threads gauge
    jvm_threads_daemon_threads 23.0
    # HELP tomcat_sessions_rejected_sessions_total
    # TYPE tomcat_sessions_rejected_sessions_total counter
    tomcat_sessions_rejected_sessions_total 0.0
    # HELP jvm_memory_committed_bytes The amount of memory in bytes that is committed for the Java virtual machine to use
    # TYPE jvm_memory_committed_bytes gauge
    jvm_memory_committed_bytes{area="heap",id="PSSurvivorSpace",} 1.31072E7
    jvm_memory_committed_bytes{area="heap",id="PSOldGen",} 1.30023424E8
    jvm_memory_committed_bytes{area="heap",id="PSEdenSpace",} 1.56762112E8
    jvm_memory_committed_bytes{area="nonheap",id="Metaspace",} 3.670016E7
    jvm_memory_committed_bytes{area="nonheap",id="CodeCache",} 7143424.0
    jvm_memory_committed_bytes{area="nonheap",id="CompressedClassSpace",} 5242880.0
    # HELP jvm_classes_loaded_classes The number of classes that are currently loaded in the Java virtual machine
    # TYPE jvm_classes_loaded_classes gauge
    jvm_classes_loaded_classes 6877.0
    # HELP jvm_threads_peak_threads The peak live thread count since the Java virtual machine started or peak was reset
    # TYPE jvm_threads_peak_threads gauge
    jvm_threads_peak_threads 28.0
    # HELP system_cpu_count The number of processors available to the Java virtual machine
    # TYPE system_cpu_count gauge
    system_cpu_count 12.0
    # HELP tomcat_sessions_expired_sessions_total
    # TYPE tomcat_sessions_expired_sessions_total counter
    tomcat_sessions_expired_sessions_total 0.0
    # HELP process_files_max_files The maximum file descriptor count
    # TYPE process_files_max_files gauge
    process_files_max_files 10240.0
    # HELP jvm_buffer_total_capacity_bytes An estimate of the total capacity of the buffers in this pool
    # TYPE jvm_buffer_total_capacity_bytes gauge
    jvm_buffer_total_capacity_bytes{id="direct",} 8192.0
    jvm_buffer_total_capacity_bytes{id="mapped",} 0.0
    # HELP jvm_threads_states_threads The current number of threads having NEW state
    # TYPE jvm_threads_states_threads gauge
    jvm_threads_states_threads{state="runnable",} 9.0
    jvm_threads_states_threads{state="blocked",} 0.0
    jvm_threads_states_threads{state="waiting",} 12.0
    jvm_threads_states_threads{state="timed-waiting",} 6.0
    jvm_threads_states_threads{state="new",} 0.0
    jvm_threads_states_threads{state="terminated",} 0.0
    # HELP jvm_buffer_count_buffers An estimate of the number of buffers in the pool
    # TYPE jvm_buffer_count_buffers gauge
    jvm_buffer_count_buffers{id="direct",} 1.0
    jvm_buffer_count_buffers{id="mapped",} 0.0
    # HELP process_files_open_files The open file descriptor count
    # TYPE process_files_open_files gauge
    process_files_open_files 93.0
    # HELP jvm_gc_memory_promoted_bytes_total Count of positive increases in the size of the old generation memory pool before GC to after GC
    # TYPE jvm_gc_memory_promoted_bytes_total counter
    jvm_gc_memory_promoted_bytes_total 5225384.0
    # HELP jvm_memory_max_bytes The maximum amount of memory in bytes that can be used for memory management
    # TYPE jvm_memory_max_bytes gauge
    jvm_memory_max_bytes{area="heap",id="PSSurvivorSpace",} 1.31072E7
    jvm_memory_max_bytes{area="heap",id="PSOldGen",} 2.863661056E9
    jvm_memory_max_bytes{area="heap",id="PSEdenSpace",} 1.40509184E9
    jvm_memory_max_bytes{area="nonheap",id="Metaspace",} -1.0
    jvm_memory_max_bytes{area="nonheap",id="CodeCache",} 2.5165824E8
    jvm_memory_max_bytes{area="nonheap",id="CompressedClassSpace",} 1.073741824E9
    # HELP jvm_gc_memory_allocated_bytes_total Incremented for an increase in the size of the (young) heap memory pool after one GC to before the next
    # TYPE jvm_gc_memory_allocated_bytes_total counter
    jvm_gc_memory_allocated_bytes_total 1.14749824E8
    # HELP jvm_classes_unloaded_classes_total The total number of classes unloaded since the Java virtual machine has started execution
    # TYPE jvm_classes_unloaded_classes_total counter
    jvm_classes_unloaded_classes_total 10.0
    # HELP tomcat_sessions_created_sessions_total
    # TYPE tomcat_sessions_created_sessions_total counter

Paso 2: Desplegar un clúster de Kubernetes

  1. Compile una imagen y cárguela a un repositorio de imágenes. Para obtener más información, consulte Connect to a source code platform.

  2. Cree un despliegue con la siguiente configuración YAML.

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: micrometer-prometheus
      namespace: default
      labels:
        app: demo-prometheus
    spec:
      replicas: 3
      selector:
        matchLabels:
          app: demo-prometheus
      template:
        metadata:
          labels:
            app: demo-prometheus
        spec:
          containers:
            - name: micrometer-prometheus
              image: manjusakalza/micrometer-prometheus:latest
              ports:
                - containerPort: 8080
  3. Cree un Service con la siguiente configuración YAML.

    apiVersion: v1
    kind: Service
    metadata:
      name: prometheus-metrics-demo
      namespace: default
      labels:
        micrometer-prometheus-discovery: 'true'
    spec:
      selector:
        app: demo-prometheus
      ports:
        - protocol: TCP
          port: 8080
          targetPort: 8080
          name: metrics

Paso 3: Crear un ServiceMonitor

  1. Guarde el archivo YAML en su computadora y ejecute kubectl apply -f {path/to/the/YAML/file} para aplicarlo.

Ejemplo de YAML de ServiceMonitor:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: micrometer-demo
  namespace: default
spec:
  endpoints:
    - interval: 15s
      path: /actuator/prometheus
      port: metrics    # Note: Configure the port name, not the port number.
  namespaceSelector:
    any: true
  selector:
    matchLabels:
      micrometer-prometheus-discovery: 'true'

Descripción de los campos YAML:

  • Los campos name y namespace dentro de metadata identifican al ServiceMonitor.

  • El campo endpoints de spec define los objetivos de recolección. Cada endpoint del arreglo endpoints (endpoints admite varias entradas) contiene estos campos:

    • interval: intervalo de recolección para este endpoint. Por ejemplo: 15s.

    • path: ruta de recolección de métricas. Por ejemplo: /actuator/prometheus.

    • port: nombre del puerto del Service (debe coincidir con el name definido en su Service de Step 2). Por ejemplo: metrics.

      Importante

      Configure el nombre del puerto, no el número de puerto.

  • El campo namespaceSelector de spec establece el alcance de detección del Service. namespaceSelector admite dos campos mutuamente excluyentes:

    • any: establézcalo en true para monitorear todos los Services coincidentes en todos los namespaces.

    • matchNames: limita el monitoreo a namespaces específicos. Por ejemplo, para monitorear únicamente los namespaces default y arms-prom, configure matchNames de la siguiente manera:

      namespaceSelector:
        matchNames:
        - default
        - arms-prom
  • El campo selector de spec filtra los Services por etiqueta.

    El Service de ejemplo tiene la etiqueta micrometer-prometheus-discovery: 'true', por lo que debe configurar selector de la siguiente manera:

    selector:
      matchLabels:
        micrometer-prometheus-discovery: 'true'

Para habilitar la autenticación básica, utilice el siguiente YAML:

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: cloud-open-api-monitor     #  Set a unique name for the ServiceMonitor.
  namespace: default   #  Set the namespace where the ServiceMonitor resides.
spec:
  endpoints:
  - interval: 30s
    # Specify the interval at which Prometheus scrapes the current endpoint.
    port: tcp-8080
    # Enter the path exposed in the Prometheus exporter code.
    path: /api/actuator/prometheus
    basicAuth:
      password:
        name: basic-auth
        key: <password>
      username:
        name: basic-auth
        key: <userName>
    scheme: http
  namespaceSelector:
    any: true
  selector:
    matchLabels:
      # Match Services with the following label.
      edas.oam.acname: cloud-open-api

Si no cuenta con permisos para la autenticación básica, cree un ClusterRole con los permisos necesarios. Luego, vincúlelo al ServiceAccount arms-prom-operator del namespace arms-prom mediante un ClusterRoleBinding.

  • Archivo YAML de ClusterRole

    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRole
    metadata:
      name: prometheus-agent-role
      labels:
        app: prometheus-agent
    rules:
      - apiGroups: [""]
        resources: ["pods", "services", "endpoints", "nodes"]
        verbs: ["get", "list", "watch"]  # Adjust as needed.
      - apiGroups: ["monitoring.coreos.com"]  # Adjust the apiGroups as needed.
        resources: ["*"]
        verbs: ["get", "list", "watch", "create", "update", "delete"]  # Adjust as needed.
    
  • Archivo YAML de ClusterRoleBinding

    apiVersion: rbac.authorization.k8s.io/v1
    kind: ClusterRoleBinding
    metadata:
      name: prometheus-agent-binding
    subjects:
      - kind: ServiceAccount
        name: arms-prom-operator  # Service account name
        namespace: arms-prom      # The namespace where the service account resides.
    roleRef:
      kind: ClusterRole
      name: prometheus-agent-role  # The name of the ClusterRole defined above.
      apiGroup: rbac.authorization.k8s.io
    

Paso 4: Comprobar el ServiceMonitor

Compruebe que Prometheus detecta su servicio:

  1. Inicie sesión en la consola de Managed Service for Prometheus. En el panel de navegación izquierdo, haga clic en Integration Management.

  2. En la pestaña Integrated Environments, haga clic en el nombre del entorno de contenedor objetivo dentro de la lista Container Service.

  3. Haga clic en la pestaña Self-Monitoring.

    En la pestaña Targets, compruebe si existe un objetivo llamado {namespace}/{serviceMonitorName}/x.

    La página muestra el grupo de objetivos default/micrometer-demo/0 (3/3 up), lo cual indica que Prometheus identificó correctamente el ServiceMonitor. Todos los objetivos presentan el estado UP en verde, lo que confirma que la configuración es válida.

  4. Expanda la fila del objetivo {namespace}/{serviceMonitorName}/x y haga clic en el enlace del endpoint.

    Compruebe que las métricas se muestren correctamente. La página muestra las métricas de ejecución de la JVM y de Tomcat en formato de exposición de Prometheus, lo que confirma que el ServiceMonitor está configurado de forma adecuada.

    # HELP jvm_buffer_total_capacity_bytes An estimate of the total capacity of the buffers in this pool
    # TYPE jvm_buffer_total_capacity_bytes gauge
    jvm_buffer_total_capacity_bytes{id="mapped",} 0.0
    jvm_buffer_total_capacity_bytes{id="direct",} 81968.0
    # HELP jvm_threads_daemon_threads The current number of live daemon threads
    # TYPE jvm_threads_daemon_threads gauge
    jvm_threads_daemon_threads 29.0
    # HELP jvm_memory_committed_bytes The amount of memory in bytes that is committed for the Java virtual machine to use
    # TYPE jvm_memory_committed_bytes gauge
    jvm_memory_committed_bytes{area="nonheap",id="miscellaneousnon-heapstorage",} 2.3068672E7
    jvm_memory_committed_bytes{area="nonheap",id="classstorage",} 2.8471712E7
    jvm_memory_committed_bytes{area="nonheap",id="JITcodecache",} 2.68435456E8
    jvm_memory_committed_bytes{area="heap",id="tenured-LOA",} 671744.0
    jvm_memory_committed_bytes{area="nonheap",id="JITdatacache",} 2097152.0
    jvm_memory_committed_bytes{area="heap",id="nursery-survivor",} 1638400.0
    jvm_memory_committed_bytes{area="heap",id="nursery-allocate",} 6881280.0
    jvm_memory_committed_bytes{area="heap",id="tenured-SOA",} 1.2763136E7
    # HELP process_start_time_seconds Start time of the process since the unix epoch.
    # TYPE process_start_time_seconds gauge
    process_start_time_seconds 1.622297808811E9
    # HELP tomcat_sessions_expired_sessions_total
    # TYPE tomcat_sessions_expired_sessions_total counter
    tomcat_sessions_expired_sessions_total 0.0
    # HELP jvm_threads_states_threads The current number of threads having NEW state
    # TYPE jvm_threads_states_threads gauge
    jvm_threads_states_threads{state="runnable",} 20.0
    jvm_threads_states_threads{state="blocked",} 0.0
    jvm_threads_states_threads{state="waiting",} 10.0
    jvm_threads_states_threads{state="timed-waiting",} 3.0
    jvm_threads_states_threads{state="new",} 0.0
    jvm_threads_states_threads{state="terminated",} 0.0
    # HELP jvm_classes_unloaded_classes_total The total number of classes unloaded since the Java virtual machine has started execution
    # TYPE jvm_classes_unloaded_classes_total counter
    jvm_classes_unloaded_classes_total 0.0
    # HELP tomcat_sessions_rejected_sessions_total
    # TYPE tomcat_sessions_rejected_sessions_total counter
    tomcat_sessions_rejected_sessions_total 0.0
    # HELP tomcat_sessions_created_sessions_total
    # TYPE tomcat_sessions_created_sessions_total counter
    tomcat_sessions_created_sessions_total 0.0
    # HELP jvm_threads_live_threads The current number of live threads including both daemon and non-daemon threads
    # TYPE jvm_threads_live_threads gauge
    jvm_threads_live_threads 33.0
    # HELP jvm_memory_max_bytes The maximum amount of memory in bytes that can be used for memory management
    # TYPE jvm_memory_max_bytes gauge