DevOps/k8s

Kubernetes 환경에 Prometheus와 Grafana를 설치하고 통합하기

Sophie소피 2024. 1. 24. 19:40

Introduction

안녕하세요. 오늘은 Kubernetes 환경에 Prometheus 및 Grafana를 설치하고 통합하는 단계를 자세히 안내하겠습니다. 이를 통해 클러스터의 모니터링 및 시각화를 손쉽게 구성할 수 있습니다.

 

Prometheus 설치

Prometheus를 설치하기 위해 Helm 차트를 사용합니다.

#Helm Repo 추가 
helm repo add prometheus-community <https://prometheus-community.github.io/helm-charts>
#Helm을 사용하여 프로메테우스 설치 
helm install prometheus prometheus-community/prometheus

 

Pod 확인

설치가 완료되면 다음 명령어를 사용하여 프로메테우스 관련 Pod가 정상적으로 배포되었는지 확인합니다.

kubectl get pods

 

 

Prometheus 서비스 노출

프로메테우스 서비스를 외부로 노출하는 부분은 클러스터 내에서 프로메테우스에 접근할 수 있도록 서비스를 노출하는 단계입니다. 이를 위해 Kubernetes에서는 Service 리소스를 사용하여 프로메테우스에 대한 외부 노출을 설정합니다.

kubectl expose service prometheus-server --type=NodePort --target-port=9090 --name=prometheus-server-np

 

 

Prometheus  활성화

Kubernetes 환경에서 Prometheus 서비스를 노출하고 웹 브라우저를 통해 해당 서비스에 액세스할 수 있도록 하는 명령어입니다. 여기서 prometheus-server-np는 서비스의 이름을 나타냅니다.

minikube service prometheus-server-np

 

 

Expose된 Service url을 통해 링크: http://127.0.0.1:62069 Prometheus를 확인할 수 있는 사이트로 진입할 수 있습니다.

 

 

 

PromQL 사용해서 namespace별 Pod 수 조회하기

kube_pod_info 쿼리는 쿠버네티스 내 파드 정보를 가져오는 쿼리입니다.

sum by (namespace) (kube_pod_info)

 

 

  • 테이블 형태로 데이터 조회

 

  • 그래프 형태로 데이터 조회

 

 

Grafana 설치

Prometheus를 설치하기 위해 Helm 차트를 사용합니다.

# **Helm Repo 추가**
helm repo add grafana <https://grafana.github.io/helm-charts>
#**Helm을 사용하여**  Grafana **설치**
helm install grafana grafana/grafana

 

 

 

Grafana 서비스 노출하기

Grafana 서비스를 외부로 노출하는 부분은 클러스터 내에서 Grafana에 접근할 수 있도록 서비스를 노출하는 단계입니다. 이를 위해 Kubernetes에서는 Service 리소스를 사용하여 Grafana에 대한 외부 노출을 설정합니다.

kubectl expose service grafana --type=NodePort --target-port=3000 --name=grafana-np

 

Grafana Pod 확인하기

설치가 완료되면 다음 명령어를 사용하여 Grafana 관련 Pod가 정상적으로 배포되었는지 확인합니다.

kubectl get pods

 

 

Grafana 활성화

환경에서 Grafana 서비스를 노출하고 웹 브라우저를 통해 해당 서비스에 액세스할 수 있도록 하는 명령어입니다. 여기서 Grafana-server-np는 서비스의 이름을 나타냅니다.

minikube service grafana-np

 

jsonpath로 Grafana 관리자 비밀번호 확인

Grafana의 관리자 비밀번호를 확인하려면, Kubernetes에서 사용되는 Secret 리소스에 저장된 비밀번호를 확인해야 합니다. Grafana의 Helm 차트를 사용한 설치 시에는 기본적으로 이러한 정보가 Secret에 저장됩니다.

다음은 kubectl 명령어와 JSONPath를 사용하여 Grafana의 관리자 비밀번호를 확인하는 예시입니다.

kubectl get secret --namespace default grafana -o jsonpath="{.data.admin-password}" | base64 --decode ; echo

 

 

Grafana에서 Prometheus 연결

Grafana에서 Prometheus와의 연결이 설정하고 대시보드를 통해 Prometheus에서 수집한 메트릭을 시각화는 방법에 대해 알아보겠습니다.

  1. Grafana에 로그인 (http://127.0.0.1:62610/login)
    • ID: admin
    • PW: [확인한 비밀번호]

 

2. 사이드 메뉴에서 Connections > Datasources 로 진입하여 "Prometheus"를 검색하여 선택합니다. 

3. URL에 프로메테우스 서버 URL 입력 (http://prometheus-server:80)

  • Name: 데이터 소스에 사용할 이름을 입력합니다.
  • HTTP: Prometheus 서버의 URL을 입력합니다. 예를 들어, http://prometheus-server:9090 또는 **http://<Prometheus 서비스 이름>:<포트>**와 같습니다.

 

 

4. "Save & Test" 버튼 클릭하고 연결이 잘되면 아래와 같은 화면이 나옵니다. 

 

 

Grafana에 대시보드 Import 하기

1. 사이드 메뉴에서 Dashboard > Create Dashboard  를 선택합니다.

 

 

2. “Import a dashboard” 를 클릭하면 Grafana 공식 사이트 Dashboard 템플릿을 사용할 수 있습니다.

 

3. Name에 템플릿 ID를 입력하여 대시보드를 Import할 수 있습니다

 

 

4. 해당 화면은 9797 템플릿을 적용한 대시보드입니다.

 

 

 

자주 쓰이는  Prometheus Alert Manager Expression 예제 

# Node ready
expr: kube_node_status_condition{condition="Ready",status="true"} == 0
 
# Memory pressure
expr: kube_node_status_condition{condition="MemoryPressure",status="true"} == 1
 
# Disk pressure
expr: kube_node_status_condition{condition="DiskPressure",status="true"} == 1
 
# Out of disk
expr: kube_node_status_condition{condition="OutOfDisk",status="true"} == 1
 
# Out of capacity
expr: sum by (node) ((kube_pod_status_phase{phase="Running"} == 1) + on(uid) group_left(node) (0 * kube_pod_info{pod_template_hash=""})) / sum by (node) (kube_node_status_allocatable{resource="pods"}) * 100 > 90
 
# Container oom killer
expr: (kube_pod_container_status_restarts_total - kube_pod_container_status_restarts_total offset 10m >= 1) and ignoring (reason) min_over_time(kube_pod_container_status_last_terminated_reason{reason="OOMKilled"}[10m]) == 1
 
# Job failed
expr: kube_job_status_failed > 0
 
# Cronjob suspended
expr: kube_cronjob_spec_suspend != 0

# PersistentVolumeClaim pending
expr: kube_persistentvolumeclaim_status_phase{phase="Pending"} == 1
 
# PersistentVolume error
expr: kube_persistentvolume_status_phase{phase=~"Failed|Pending", job="kube-state-metrics"} > 0

# StatefulSet down
expr: (kube_statefulset_status_replicas_ready / kube_statefulset_status_replicas_current) != 1
 
# Readiness probe 실패
expr : sum by(pod)( kube_pod_info{created_by_kind!="Job"} AND ON (pod, namespace) kube_pod_status_ready{condition="false"} == 1) > 0
 
# HPA scaling ability
kube_horizontalpodautoscaler_status_condition{status="false", condition="AbleToScale"} == 1
 
# Pod not healthy
min_over_time(sum by (namespace, pod) (kube_pod_status_phase{phase=~"Pending|Unknown|Failed"})[15m:1m]) > 0
 
# Pod crash looping
expr: increase(kube_pod_container_status_restarts_total[1m]) > 3

 

 

Grafana 공식 템플릿 사이트

https://grafana.com/grafana/dashboards/

 

Dashboards | Grafana Labs

Thank you! Your message has been received!

grafana.com

 

지금까지 Kubernetes 환경에 Prometheus 및 Grafana를 설치하고 통합하는 과정을 자세하게 살펴보았습니다. 클러스터의 모니터링 및 시각화를 구성하는 해당 가이드를 통해 여러분도 손쉽게 모니터링 환경을 구축할 수 있습니다. 오픈소스 이제 두렵지 않다!