Cloud/Monitoring

Prometheus 설치하기

freestrokes 2021. 9. 16. 16:53
반응형

 

Prometheus 설치하기

 

Helm 차트를 이용하여 Prometheus를 설치하는 방법에 대해 알아보겠습니다. (Docker Desktop에서 구성한 Kubernetes 환경에 설치한 내용을 정리했습니다)

 

 

1. Prometheus 구성


Prometheus는 음악 스트리밍 플랫폼 Soundcloud에서 만든 모니터링 툴킷입니다. 다음과 같은 특징을 가지고 있습니다.

 

  • 다차원 모델
    key/value 쌍과 메트릭 이름으로 식별 가능한 시계열 데이터 지원
  • PromQL
    차원 활용을 위한 유연한 쿼리 언어 지원
  • 단일 서버 노드
    분산 저장 장치에 의존적이지 않은 자율적인 동작 지원
  • HTTP pull 모델을 이용한 시계열 데이터 수집
  • 서비스 검색 또는 정적 구성을 통한 대상 탐색
  • 중개 게이트웨이(Pushgateway)를 이용한 메트릭 pushing 지원
  • 다양한 그래프 및 대시보드 지원

 

구조는 다음과 같습니다. 프로메테우스 서버가 각각의 노드(컴포넌트)가 수집한 데이터를 가져오는 구조입니다. 서버에서 클라이언트가 동작중인 상태를 확인하면 주기적으로 클라이언트에 접속해서 데이터를 가져오는 pull 방식으로 동작합니다. 

 

Prometheus Architecture

 

또한 프로메테우스는 다음과 같은 컴포넌트들로 구성됩니다.

 

  • Prometheus Server
    데이터를 수집하고 저장하는 메인 서버.
  • Exporter
    target 메트릭 데이터 수집.
    HTTP 엔드포인트를 설정하여 서버에서 메트릭을 수집하도록 지원.
    HAProxy, StatsD, Graphite와 같은 서비스를 지원.  
  • Alertmanager
    설정한 규칙에 따른 알림 처리
  • Pushgateway
    Exporter를 이용하여 수집이 어려운 작업에 대한 메트릭 pushing 지원.
  • Grafana
    데이터 시각화를 위한 Web UI 및 대시보드 지원
  • Client Libraries
    Java, Scala, Go, Python, Ruby 등의 언어에 대한 프로메테우스 연동 라이브러리

 

 

2. Prometheus 설치


2.1. Helm을 이용한 Prometheus 설치

 

Prometheus 설치를 위해 Helm Repository를 추가해줍니다.

$ helm repo add prometheus-community https://prometheus-community.github.io/helm-charts

 

Prometheus Helm Chart를 다운로드 해줍니다.

$ git clone https://github.com/prometheus-community/helm-charts

 

values.yaml 파일이 있는 위치로 이동해줍니다.

$ cd helm-charts/charts/prometheus

 

로컬 환경에서의 설치를 위해 values.yaml 파일을 열어서 PV(Persistent Volume) 설정을 false로 변경해줍니다. alertmanager, pushgateway, prometheus server에 대해 enabled 값을 false로 변경해줍니다. PV, PVC를 설정하지 않고 배포하면 Pending 상태가 되기 때문에 변경이 필요하지만 실제 운영 환경에서는 PV를 설정해주는 것이 권장됩니다.

$ vi values.yaml

...
  persistentVolume:
    ## If true, alertmanager will create/use a Persistent Volume Claim
    ## If false, use emptyDir
    ##
    enabled: false
...
  persistentVolume:
    ## If true, pushgateway will create/use a Persistent Volume Claim
    ##
    enabled: false
...
  persistentVolume:
    ## If true, Prometheus server will create/use a Persistent Volume Claim
    ## If false, use emptyDir
    ##
    enabled: false
...

 

Docker Desktop 쿠버네티스 환경에서 설치하는 경우에는 PV 설정 이후에 nodeExporter 항목에서 hostRootfs 값을 false로 변경해줍니다. rootfs의 마운트 경로를 지정하는 부분인데 Window 또는 Mac에서 Docker Desktop을 이용하여 프로메테우스를 설치하는 경우에 node-exporter가 CrashLoopBackOff 상태가 되는 문제가 발생합니다. (마찬가지로 운영 환경에서는 이상없도록 설정해주는 것이 좋습니다)

$ vi values.yaml

...
nodeExporter:
  ...
  ## If true, node-exporter pods mounts host / at /host/root
  ##
  hostRootfs: false
...
 

[kube-prometheus-stack] node-exporter crashes at startup · Issue #467 · prometheus-community/helm-charts

Describe the bug Node exporter pod underlying container fails to startup. This is the error reported by the deamon: Error: failed to start container "node-exporter": Error response from d...

github.com

 

다음으로 서비스를 브라우저에서 확인하기 위해 ClusterIP를 NodePort로 변경해줍니다. 위와 마찬가지로 values.yaml 파일에서 service 부분을 찾아 변경해줍니다.

$ vi values.yaml

...

nodeExporter:
  ## If false, node-exporter will not be installed
  ##
  enabled: true
  
  ... 
  
  service:
    annotations: {}
    labels: {}
    clusterIP: ""

    ## Enabling peer mesh service end points for enabling the HA alert manager
    ## Ref: https://github.com/prometheus/alertmanager/blob/master/README.md
    # enableMeshPeer : true

    ## List of IP addresses at which the alertmanager service is available
    ## Ref: https://kubernetes.io/docs/user-guide/services/#external-ips
    ##
    externalIPs: []

    loadBalancerIP: ""
    loadBalancerSourceRanges: []
    servicePort: 80
    nodePort: 31000
    sessionAffinity: None
    type: NodePort
    #type: ClusterIP

...

server:
  ## Prometheus server container name
  ##
  enabled: true
  
  ...
  
  service:
    annotations: {}
    labels: {}
    clusterIP: ""

    ## List of IP addresses at which the Prometheus server service is available
    ## Ref: https://kubernetes.io/docs/user-guide/services/#external-ips
    ##
    externalIPs: []

    loadBalancerIP: ""
    loadBalancerSourceRanges: []
    servicePort: 80
    nodePort: 31090
    sessionAffinity: None
    type: NodePort
    #type: ClusterIP

...

pushgateway:
  ## If false, pushgateway will not be installed
  ##
  enabled: true

  ... 
  
  service:
    annotations:
      prometheus.io/probe: pushgateway
    labels: {}
    clusterIP: ""

    ## List of IP addresses at which the pushgateway service is available
    ## Ref: https://kubernetes.io/docs/user-guide/services/#external-ips
    ##
    externalIPs: []

    loadBalancerIP: ""
    loadBalancerSourceRanges: []
    servicePort: 9091
    nodePort: 31091
    type: NodePort
    #type: ClusterIP
    
...

 

네임스페이스를 생성하고 helm으로 프로메테우스를 설치해줍니다.

$ kubectl create namespace monitoring
$ helm install prometheus prometheus-community/prometheus -f values.yaml --namespace monitoring

NAME: prometheus
LAST DEPLOYED: Thu Sep 16 16:10:52 2021
NAMESPACE: monitoring
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
The Prometheus server can be accessed via port 80 on the following DNS name from within your cluster:
prometheus-server.monitoring.svc.cluster.local


Get the Prometheus server URL by running these commands in the same shell:
  export NODE_PORT=$(kubectl get --namespace monitoring -o jsonpath="{.spec.ports[0].nodePort}" services prometheus-server)
  export NODE_IP=$(kubectl get nodes --namespace monitoring -o jsonpath="{.items[0].status.addresses[0].address}")
  echo http://$NODE_IP:$NODE_PORT
#################################################################################
######   WARNING: Persistence is disabled!!! You will lose your data when   #####
######            the Server pod is terminated.                             #####
#################################################################################


The Prometheus alertmanager can be accessed via port 80 on the following DNS name from within your cluster:
prometheus-alertmanager.monitoring.svc.cluster.local


Get the Alertmanager URL by running these commands in the same shell:
  export NODE_PORT=$(kubectl get --namespace monitoring -o jsonpath="{.spec.ports[0].nodePort}" services prometheus-alertmanager)
  export NODE_IP=$(kubectl get nodes --namespace monitoring -o jsonpath="{.items[0].status.addresses[0].address}")
  echo http://$NODE_IP:$NODE_PORT
#################################################################################
######   WARNING: Persistence is disabled!!! You will lose your data when   #####
######            the AlertManager pod is terminated.                       #####
#################################################################################
#################################################################################
######   WARNING: Pod Security Policy has been moved to a global property.  #####
######            use .Values.podSecurityPolicy.enabled with pod-based      #####
######            annotations                                               #####
######            (e.g. .Values.nodeExporter.podSecurityPolicy.annotations) #####
#################################################################################


The Prometheus PushGateway can be accessed via port 9091 on the following DNS name from within your cluster:
prometheus-pushgateway.monitoring.svc.cluster.local


Get the PushGateway URL by running these commands in the same shell:
  export NODE_PORT=$(kubectl get --namespace monitoring -o jsonpath="{.spec.ports[0].nodePort}" services prometheus-pushgateway)
  export NODE_IP=$(kubectl get nodes --namespace monitoring -o jsonpath="{.items[0].status.addresses[0].address}")
  echo http://$NODE_IP:$NODE_PORT

For more information on running Prometheus, visit:
https://prometheus.io/

 

설치가 완료되면 pod과 service를 확인해줍니다.

$ kubectl get pods --namespace monitoring

NAME                                             READY   STATUS    RESTARTS   AGE
prometheus-alertmanager-56bf589d87-9qc4g         2/2     Running   0          27m
prometheus-kube-state-metrics-76f66976cb-kr4sj   1/1     Running   0          27m
prometheus-node-exporter-kk2cg                   1/1     Running   0          15m
prometheus-pushgateway-598d657c9-t8wwv           1/1     Running   0          27m
prometheus-server-6d4f656cc8-cv9m6               2/2     Running   0          27m
$ kubectl get services --namespace monitoring

NAME                            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
prometheus-alertmanager         NodePort    10.96.212.194    <none>        80:31000/TCP     27m
prometheus-kube-state-metrics   ClusterIP   10.106.133.230   <none>        8080/TCP         27m
prometheus-node-exporter        ClusterIP   None             <none>        9100/TCP         27m
prometheus-pushgateway          NodePort    10.96.244.72     <none>        9091:32630/TCP   27m
prometheus-server               NodePort    10.105.233.33    <none>        80:31090/TCP     27m

 

 

2.2. Prometheus Web UI 확인

 

설치가 완료되면 브라우저에 접속하여 프로메테우스를 확인해줍니다. prometheus-server에 설정한 포트로 접속해줍니다.

Prometheus Server in web

 

상단에서 Status > Targets 메뉴를 클릭하면 프로메테우스가 메트릭을 수집해오는 모듈들을 확인할 수 있습니다.

Prometheus Targets

 

Graph 탭에서 원하는 메트릭을 입력해서 실행하면 다음과 같이 테이블과 그래프 형태로 조회가 가능합니다.

Metrics in table
Metrics in Graph

 

이상으로 Kubernetes 클러스터에 Prometheus를 설치하는 방법에 대해 알아봤습니다.

 

 

※ Reference

 

 

반응형