ServiceMonitor

O que é o ServiceMonitor?

O ServiceMonitor é um recurso do Prometheus Operator que permite que você configure o Prometheus para monitorar um serviço. Ele é um Custom Resource Definition (CRD) que pode ser criado no Kubernetes.

Criando o Deployment e o Service para serem utilizados com o ServiceMonitor

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-server
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "9113"
    spec:
      containers:
      - name: nginx
        image: nginx
        ports:
        - containerPort: 80
          name: http
        volumeMounts:
        - name: nginx-config
          mountPath: /etc/nginx/conf.d/default.conf
          subPath: nginx.conf
      - name: nginx-exporter
        image: "nginx/nginx-prometheus-exporter:0.11.0"
        args:
        - "-nginx.scrape-uri=http://localhost/metrics"
        resources:
          requests:
            cpu: 0.1
            memory: 64Mi
          limits:
            cpu: 0.3
            memory: 128Mi
        ports:
        - containerPort: 9113
          name: metrics
      volumes:
        - configMap:
            defaultMode: 420
            name: nginx-config
          name: nginx-config
apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config
data:
  nginx.conf: |
    server {
      listen 80;
      location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
      }
      location /metrics {
        stub_status on;
        access_log off;
      }
    }    
apiVersion: v1
kind: Service
metadata:
  name: nginx-server
  labels:
    app: nginx
spec:
  selector:
    app: nginx
  ports:
  - name: http
    port: 80
    targetPort: 80
  - name: metrics
    port: 9113
    targetPort: 9113

Criando o ServiceMonitor

apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: nginx-service-monitor
  labels:
    app: nginx
spec:
  selector:
    matchLabels:
      app: nginx
  endpoints:
  - port: metrics
    interval: 30s
    path: /metrics
    targetPort: 9113