ローカルKubernetesクラスター上でPrometheusのメトリクスをGrafanaダッシュボードで可視化する
記事の内容
Prometheusで収集したメトリクスをGrafana上で可視化する構成をローカルKubernetesクラスター上で行います。
記事の長さ
5分で読めます
Kubernetesクラスターを構築する
まずは、Kubernetesクラスターを起動します。(今回はkindを利用します)
kindクラスターの作成
$ kind create cluster --name prometheus-grafana-metrics
Creating cluster "prometheus-grafana-metrics" ...
 ✓ Ensuring node image (kindest/node:v1.27.3) 🖼
 ✓ Preparing nodes 📦
 ✓ Writing configuration 📜
 ✓ Starting control-plane 🕹️
 ✓ Installing CNI 🔌
 ✓ Installing StorageClass 💾
Set kubectl context to "kind-prometheus-grafana-metrics"
You can now use your cluster with:
kubectl cluster-info --context kind-prometheus-grafana-metrics
Thanks for using kind! 😊
$ kubectl get ns
NAME                 STATUS   AGE
default              Active   115s
kube-node-lease      Active   115s
kube-public          Active   115s
kube-system          Active   115s
local-path-storage   Active   111s
正常にKubernetesクラスターを起動できました!
GrafanaをInstallする
まずは、GrafanaをkindクラスターにInstallします。
Grafana Install
公式チュートリアル通り進めます。
grafana namespaceの作成
$ kubectl create namespace my-grafana
grafanaのmanifestを作成
$ touch grafana.yaml
grafana.yaml
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: grafana-pvc
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: grafana
  name: grafana
spec:
  selector:
    matchLabels:
      app: grafana
  template:
    metadata:
      labels:
        app: grafana
    spec:
      securityContext:
        fsGroup: 472
        supplementalGroups:
          - 0
      containers:
        - name: grafana
          image: grafana/grafana:latest
          imagePullPolicy: IfNotPresent
          ports:
            - containerPort: 3000
              name: http-grafana
              protocol: TCP
          readinessProbe:
            failureThreshold: 3
            httpGet:
              path: /robots.txt
              port: 3000
              scheme: HTTP
            initialDelaySeconds: 10
            periodSeconds: 30
            successThreshold: 1
            timeoutSeconds: 2
          livenessProbe:
            failureThreshold: 3
            initialDelaySeconds: 30
            periodSeconds: 10
            successThreshold: 1
            tcpSocket:
              port: 3000
            timeoutSeconds: 1
          resources:
            requests:
              cpu: 250m
              memory: 750Mi
          volumeMounts:
            - mountPath: /var/lib/grafana
              name: grafana-pv
      volumes:
        - name: grafana-pv
          persistentVolumeClaim:
            claimName: grafana-pvc
---
apiVersion: v1
kind: Service
metadata:
  name: grafana
spec:
  ports:
    - port: 3000
      protocol: TCP
      targetPort: http-grafana
  selector:
    app: grafana
  sessionAffinity: None
  type: LoadBalancer
上記マニフェストファイルをapplyします。
$ kubectl apply -f grafana.yaml --namespace=my-grafana
persistentvolumeclaim/grafana-pvc created
deployment.apps/grafana created
service/grafana created
Grafanaの管理画面にアクセスする
上記のInstallフローが完了したら、GrafanaにPort-Forwardを利用して、アクセスします。
$ kubectl port-forward service/grafana 3000:3000 --namespace=my-grafana
上記コマンドを実行後、http://localhost:3000 にアクセスします。
すると、以下のようなGrafanaの初期画面が表示されます。

Loginする
Grafanaの初期ユーザーとPasswordは以下になります。
- id: admin
- password: admin
上記情報をログイン情報として入力すると、Grafanaの初期ダッシュボードが表示されます。

PrometheusをInstallする
GrafanaのInstallが完了したため、次にPrometheusをKubernetesクラスターにInstallします。
PrometheusのInstall
Grafanaの公式ドキュメントがPromehteusのSetupについての記事も公開しているため、こちらに従って行います。
Prometheus OperatorのInstall
Promehteus OperatorをInstallします。
$ kubectl create -f https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/master/bundle.yaml
customresourcedefinition.apiextensions.k8s.io/alertmanagerconfigs.monitoring.coreos.com created
customresourcedefinition.apiextensions.k8s.io/alertmanagers.monitoring.coreos.com created
customresourcedefinition.apiextensions.k8s.io/podmonitors.monitoring.coreos.com created
customresourcedefinition.apiextensions.k8s.io/probes.monitoring.coreos.com created
customresourcedefinition.apiextensions.k8s.io/prometheusagents.monitoring.coreos.com created
customresourcedefinition.apiextensions.k8s.io/prometheuses.monitoring.coreos.com created
customresourcedefinition.apiextensions.k8s.io/prometheusrules.monitoring.coreos.com created
customresourcedefinition.apiextensions.k8s.io/scrapeconfigs.monitoring.coreos.com created
customresourcedefinition.apiextensions.k8s.io/servicemonitors.monitoring.coreos.com created
customresourcedefinition.apiextensions.k8s.io/thanosrulers.monitoring.coreos.com created
clusterrolebinding.rbac.authorization.k8s.io/prometheus-operator created
clusterrole.rbac.authorization.k8s.io/prometheus-operator created
deployment.apps/prometheus-operator created
serviceaccount/prometheus-operator created
service/prometheus-operator created
RBACを設定する
次に、Promehteusを扱うServiceAccountのRBAC設定を行います。
$ touch prom_rbac.yaml
prom_rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: prometheus
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: prometheus
rules:
- apiGroups: [""]
  resources:
  - nodes
  - nodes/metrics
  - services
  - endpoints
  - pods
  verbs: ["get", "list", "watch"]
- apiGroups: [""]
  resources:
  - configmaps
  verbs: ["get"]
- apiGroups:
  - networking.k8s.io
  resources:
  - ingresses
  verbs: ["get", "list", "watch"]
- nonResourceURLs: ["/metrics"]
  verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: prometheus
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: prometheus
subjects:
- kind: ServiceAccount
  name: prometheus
  namespace: default
$ kubectl apply -f prom_rbac.yaml
serviceaccount/prometheus created
clusterrole.rbac.authorization.k8s.io/prometheus created
clusterrolebinding.rbac.authorization.k8s.io/prometheus created
PrometheusをDeployする
Prometheus OperatorとRBACの設定が完了したので、Prometheusサーバーをデプロイします。
$ touch prometheus.yaml
prometheus.yaml
apiVersion: monitoring.coreos.com/v1
kind: Prometheus
metadata:
  name: prometheus
  labels:
    app: prometheus
spec:
  image: quay.io/prometheus/prometheus:v2.22.1
  nodeSelector:
    kubernetes.io/os: linux
  replicas: 2
  resources:
    requests:
      memory: 400Mi
  securityContext:
    fsGroup: 2000
    runAsNonRoot: true
    runAsUser: 1000
  serviceAccountName: prometheus
  version: v2.22.1
  serviceMonitorSelector: {}
$ kubectl apply -f prometheus.yaml
prometheus.monitoring.coreos.com/prometheus created
Serviceを作成する
Prometheusのデプロイが完了したため、Prometheusのサービスを作成して、他のサービスからPrometheusにアクセスできるようにします。
$ touch prom_svc.yaml
prom_svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: prometheus
  labels:
    app: prometheus
spec:
  ports:
  - name: web
    port: 9090
    targetPort: web
  selector:
    app.kubernetes.io/name: prometheus
  sessionAffinity: ClientIP
$ kubectl apply -f prom_svc.yaml
service/prometheus created
Prometheusにアクセスしてみる
PrometheusのInstallが完了したので、Prometheusの管理画面にアクセスします。
$ kubectl port-forward svc/prometheus 9090
上記コマンドでPort-Forwardを実行し、http://localhost:9090 にアクセスすると、以下のようなPrometheusの管理画面が表示されます。

Grafana, Prometheusの準備が完了
これで2つのツールの準備が完了しました。
正常にPrometheusで収集したメトリクスをGrafanaに表示できるかどうかを試すために、Prometheus自身のメトリクスをGrafanaに表示して実験します。
ServiceMonitorを追加する
PrometheusのServiceMonitorリソースを追加します。ServiceMonitorはサービスディスカバリの役割を果たし、Prometheusのスクレイピング詳細を設定できます。
$ touch prometheus_servicemonitor.yaml
prometheus_servicemonitor.yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: prometheus-self
  labels:
    app: prometheus
spec:
  endpoints:
  - interval: 30s
    port: web
  selector:
    matchLabels:
      app: prometheus
$ kubectl apply -f prometheus_servicemonitor.yaml
servicemonitor.monitoring.coreos.com/prometheus-self created
Prometheus上でメトリクスを確認する
上記ServiceMonitorで設定したターゲットが正常にPrometheusサーバーに取り込まれているかを確認するために、Prometheusの管理画面で確認します。
※PrometheusサーバーにPort-Forwardを実行してください。
Target

http://localhost:9090/targets にアクセスすると、↑のように今回追加したprometheus-selfというターゲットが表示されます。
Metrics

メトリクスも正常に表示されることが確認できます。
正常にServiceMonitorが動作していることを確認できました。
GrafanaでPrometheusのデータを可視化する
Prometheus上で正常にメトリクスの確認ができたため、そのメトリクスをGrafanaで表示します。
DatasourcesにPrometheusを追加する
Grafanaのダッシュボード上でData Sourceを追加します。

このように、Connectionの欄に、先ほどPrometheusの画面で確認したターゲットのエンドポイントを入力して、Datasourceを作成してください。
Dashboardを作成する
今作成したDatasourcesを元にDashboardを作成します。
Dashboard画面から、Dashboardの作成を行い、先ほど作成したPrometheus Data Sourceを選択し、適当なMetricsを選択してクエリを実行します。

上記のように先ほどPrometheus上で確認したメトリクスと同じメトリクスがGrafana上で可視化できました。
まとめ
これで、Prometheusで管理するメトリクスをGrafanaで表示することができました。
sampleソース
今回作成したプロジェクトのマニフェストファイルは以下に配置してあります。
note
勉強法やキャリア構築法など、エンジニアに役立つ記事をnoteで配信しています。




Discussion