세상에서 제일 쉬운 Prometheus - Grafana 모니터링 설정

sojukang·2022년 7월 27일
0

Node Exporter - Prometheus - Grafana 모니터링 과정

Node Exporter는 스파이와 같습니다. 우리가 모니터링을 원하는 서버에 투입하여 관련 정보를 모읍니다.
Prometheus는 국정원과 같습니다. Node Exporter 등 서버의 정보(metrics)를 모은 스파이들에게 주기적으로 pull 요청을 하여 metrics를 수집합니다.
Garafana는 모은 정보를 바탕으로 시각화하는 도구입니다. 이번 글에서는 먼저 Node Exporter, Spring Actuator 스파이를 Spring이 띄워진 WAS에 심고, 별도로 구성된 모니터링 서버로 metrics를 수집하고 시각화하는 과정을 다뤄봅시다.

Node Exporter

Node Exporter 설치

먼저 우리가 관찰할 서버에 스파이인 Node Exporter를 설치해줍시다.
Node Exporter github repository
Node Exporter 공식 repository에서 현재까지 나온 버전을 확인 후 내 서버 환경에 맞는 버전을 찾아봅시다.
저희는 Linux ubuntu 22.04, Arm64 기반 CPU 환경에서 1.3.1 버전으로 진행해보겠습니다. Arm64 기반이 아닌 경우 binary 파일 읽기 오류가 발생합니다. 맞는 버전을 설치하거나 docker 등 가상 환경에서 설치를 진행하면 됩니다.

wget https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_exporter-1.3.1.linux-arm64.tar.gz

다운 받은 뒤 압축을 풀고 압축 파일은 지워줍시다.

tar xvfz node_exporter-1.3.1.linux-arm64.tar.gz

Node Exporter 실행

이제 Node Exporter를 실행해봅시다.
Node Exporter가 설치된 디렉토리에서 다음 명령어를 적용해봅시다.

nohup ./node_exporter --web.listen-address=:8081 &

nohup은 백그라운드 실행을 위해, --web.listen-address=:8081는 Node Exporter를 8081 포트로 연결하기 위한 명령어입니다.

이제 {ip}:8081/metrics로 접근하면 Node exporter에 의해 수집된 metrics들을 볼 수 있습니다. 이제 이 스파이가 쌓은 정보를 Prometheus가 수집할 겁니다.

Spring-actuator 설정

Spring Application 모니터링을 위해 actuator 설정을 해봅시다.

	implementation 'org.springframework.boot:spring-boot-starter-actuator'
	implementation 'io.micrometer:micrometer-registry-prometheus'

build.gradle에 다음 설정을 추가해 줍시다.

# actuator
management.endpoints.web.exposure.include=health, info, prometheus

application.properties에 다음 옵션을 추가해줍시다. default 설정 외 health, info, prometheus 관련 metrics를 노출합니다.

혹시 문서 자동화 툴인 Swagger를 사용중인데 오류가 뜬다면

    @Bean
    public WebMvcEndpointHandlerMapping webEndpointServletHandlerMapping(WebEndpointsSupplier webEndpointsSupplier,
        ServletEndpointsSupplier servletEndpointsSupplier, ControllerEndpointsSupplier controllerEndpointsSupplier,
        EndpointMediaTypes endpointMediaTypes, CorsEndpointProperties corsProperties,
        WebEndpointProperties webEndpointProperties, Environment environment) {
        List<ExposableEndpoint<?>> allEndpoints = new ArrayList();
        Collection<ExposableWebEndpoint> webEndpoints = webEndpointsSupplier.getEndpoints();
        allEndpoints.addAll(webEndpoints);
        allEndpoints.addAll(servletEndpointsSupplier.getEndpoints());
        allEndpoints.addAll(controllerEndpointsSupplier.getEndpoints());
        String basePath = webEndpointProperties.getBasePath();
        EndpointMapping endpointMapping = new EndpointMapping(basePath);
        boolean shouldRegisterLinksMapping = this.shouldRegisterLinksMapping(webEndpointProperties, environment,
            basePath);
        return new WebMvcEndpointHandlerMapping(endpointMapping, webEndpoints, endpointMediaTypes,
            corsProperties.toCorsConfiguration(), new EndpointLinksResolver(allEndpoints, basePath),
            shouldRegisterLinksMapping, null);
    }

    private boolean shouldRegisterLinksMapping(WebEndpointProperties webEndpointProperties, Environment environment,
        String basePath) {
        return webEndpointProperties.getDiscovery().isEnabled() && (StringUtils.hasText(basePath)
            || ManagementPortType.get(environment).equals(ManagementPortType.DIFFERENT));
    }

위 코드를 Swagger 관련 Config 파일에 넣으면 해결할 수 있습니다.

Prometheus

Prometheus 설치

Prometheus 공식 repository에서 현재까지 나온 버전을 확인 후 내 서버 환경에 맞는 버전을 찾아봅시다.
prometheus github repository
위와 동일한 환경에서 2.37.0 버전으로 진행해보겠습니다.

wget https://github.com/prometheus/prometheus/releases/download/v2.37.0/prometheus-2.37.0.linux-arm64.tar.gz

다운 받은 뒤 압축을 풀고 압축 파일은 지워줍시다.
생성된 디렉토리로 들어가 prometheus.yml 설정 파일을 조정해봅시다.

# my global config
global:
  scrape_interval: 15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: "develop-linux"

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
      - targets: ["{ip}:{port}"]

  - job_name: "develop-spring-boot"
    metrics_path: "/actuator/prometheus"
    static_configs:
      - targets: ["{ip}:{port}"]

기본으로 exporter로부터 데이터를 pull 해오는 주기는 15s인 것을 확인할 수 있습니다. 조정이 필요한 경우 조정해줍시다.
job_name을 기준으로 여러 job들을 구분할 수 있습니다. 위 설정 파일은 develop 리눅스 서버의 metrics exporter를 8081 포트로 접근하여 pull해오고, develop 서버의 Spring actuator에 의해 생성된 metrics를 8080 포트로 접근하여 가져오고 있습니다.
actuator로 생성되는 metrics는 metrics_path/actuator/prometheus를 더해 접근하는 것을 유의합시다({ip}:8080/actuator/prometheus).

Prometheus 실행

이제 Prometheus를 실행해봅시다.
Prometheus가 설치된 디렉토리에서 다음 명령어를 적용해봅시다.

nohup ./prometheus --config.file=prometheus.yml --web.listen-address=:8080 > prometheus.log 2>&1 &

nohup은 백그라운드 실행을 위해, --config.file=prometheus.yml는 실행 파일 적용을 위해, --web.listen-address=:8080는 Prometheus의 기본 포트인 9090에서 8080으로 변경하기 위해, > prometheus.log 2>&1 &는 log 파일을 남기기 위한 명령어입니다.

실행이 되었으면 {ip}:{Promethues port number}로 접근해봅시다.

Prometheus를 실행시켰습니다! 여기서 당황하지 말고 Status 탭의 Targets으로 들어가봅시다.

연결이 잘된경우 녹색 UP이, 아닌 경우 적색 DOWN 을 볼 수 있습니다.

앞서 메인 페이지에서 기록된 metrics를 쿼리 별로 볼 수 있지만, 여기서는 Grafana를 통해 깔끔하게 시각화해서 보겠습니다.

Grafana

Grafana 설치

Grafana도 앞선 Prometheus 설치와 매우 유사합니다.
Grafana Download Page
위와 동일한 환경에서 최신 버전인 9.0.5를 설치해보겠습니다.

wget https://dl.grafana.com/enterprise/release/grafana-enterprise-9.0.5.linux-arm64.tar.gz

압축을 풀고 압축 파일 삭제 후 생성된 디렉토리의 /conf/default.ini 설정 파일을 열어서 수정해봅시다. 꽤나 긴 설정 파일이지만 이번에 수정할 것은 defualt port입니다.

# The http port to use
http_port = 8081

Grafana 실행

Grafana는 기본적으로 3000 포트를 사용하기 때문에 설정된 서버 보안 규칙상 8081로 바꿔서 실행해보겠습니다.
이제 /bin/grafana-server를 실행해봅시다.

nohup ./grafana-server > grafana.log 2>&1 &

명령어 설명은 위와 같으니 생략합니다.

이제 {ip}:8081로 들어가면 로그인 화면이 반기고 있을 겁니다.
초기 설정은 id: admin, password: admin 입니다. 마음 가는 대로 바꿔줍시다

처음 들어가면 꽤나 막막합니다. 자료를 찾아보면 깔끔하게 온갖 metrics들을 그래프로 보던데... 하나하나 설정하려니 막막합니다. 우리는 여러 고마우신 분들이 만들어 놓은 Dashboards를 사용해보겠습니다.
Grafana Dashboards

Linux 서버 모니터링을 위해 Node exporter Full, JVM
Spring boot 모니터링을 위해 Spring Boot 2.1 System Monitor를 받아오겠습니다. 적용 방법은 페이지에서 Copy id to clipboard를 통해 id를 복사하고, Grafana에서 Dashboards -> +import에 진입하여

위와 같이 import 해주면 됩니다. 이제 import된 Dashboards를 확인해보면

위와 같이 깔끔하게 서버의 상태를 모니터링 할 수 있고,

여러 metrics들을 모니터링 할 수 있습니다. 위 Dashboard는 Node Exporter Full입니다.

다음 글에는 Alertmanager를 통해 상황 발생시 email 등 알림 설정에 대해 알아보겠습니다🤸‍♂️.

참고

Node Exporter docs
Prometheus docs
Grafana docs

[Prometheus] 프로메테우스 설치 / Node Exporter 메트릭 데이터수집
Prometheus 를 이용한 모니터링 — Part 1
Prometheus를 통한 서버 모니터링
프로메테우스(Prometheus) 알아보기
actuator status: 404

profile
기계공학과 개발어린이

0개의 댓글