---
# System prepended metadata

title: Rancher Monitoring 建立 ServiceMonitor
tags: [工具]

---

# Rancher Monitoring 建立 ServiceMonitor

## ServiceMonitor

![image](https://hackmd.io/_uploads/ryO9k_3f1e.png)

* ServiceMonitor 用於定義在 Kubernetes 內部從其獲取指標的應用程序，控制器將處理我們定義的 ServiceMonitor 並自動構建所需的 Prometheus 配置。


```
$ kubectl get servicemonitor -A
NAMESPACE                  NAME                                          AGE
cattle-monitoring-system   rancher-monitoring-alertmanager               113d
cattle-monitoring-system   rancher-monitoring-grafana                    113d
cattle-monitoring-system   rancher-monitoring-kube-controller-manager    113d
cattle-monitoring-system   rancher-monitoring-kube-etcd                  113d
cattle-monitoring-system   rancher-monitoring-kube-proxy                 113d
cattle-monitoring-system   rancher-monitoring-kube-scheduler             113d
cattle-monitoring-system   rancher-monitoring-kube-state-metrics         113d
cattle-monitoring-system   rancher-monitoring-operator                   113d
cattle-monitoring-system   rancher-monitoring-prometheus                 113d
cattle-monitoring-system   rancher-monitoring-prometheus-node-exporter   113d
default                    rancher-monitoring-apiserver                  113d
istio-system               envoy-stats-monitor                           70d
istio-system               istio-component-monitor                       70d
kube-system                rancher-monitoring-coredns                    113d
kube-system                rancher-monitoring-ingress-nginx              113d
kube-system                rancher-monitoring-kubelet                    113d
```


## 實作
* 先建立應用
```
$ echo 'apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-app
spec:
  replicas: 3
  selector:
    matchLabels:
      app: example-app
  template:
    metadata:
      labels:
        app: example-app
    spec:
      containers:
      - name: example-app
        image: quay.io/brancz/prometheus-example-app:v0.5.0
        ports:
        - name: web
          containerPort: 8080
---
kind: Service
apiVersion: v1
metadata:
  name: example-app
  labels:
    app: example-app
spec:
  selector:
    app: example-app
  ports:
  - name: web
    port: 8080' | kubectl apply -f -
```

* 建立 ServiceMonitor，他會去監控帶有 `app: example-app` label 的 service。
```
$ echo 'apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: example-app
  labels:
    team: frontend
spec:
  selector:
    matchLabels:
      app: example-app
  endpoints:
  - port: web' | kubectl apply -f -
```
```
$ kubectl get servicemonitor
NAME                           AGE
example-app                    9s
rancher-monitoring-apiserver   74d
```
* 透過 Rancher UI 進到 Prometheus Targets，搜尋 ServiceMonitor 名稱，可以找到目前監控有哪些物件

![image](https://hackmd.io/_uploads/rJUTx_hzkl.png)


## 參考 

https://github.com/prometheus-operator/prometheus-operator/blob/main/Documentation/user-guides/getting-started.md