본문 바로가기

Project/Nuwa

Nuwa Project - Monitoring (Actuator & Prometheus & Grafana)

반응형
SMALL
SMALL
반응형

프로젝트를 진행을 할 때 모니터링이 필요하다고 느껴졌습니다.

오류는 Sentry를 사용해서 보고 있었기 때문에 문제는 따로 없었지만

서버 로그를 확인을 하려면 서버에 접속을 해서 확인을 해야되는 문제점이 생겼습니다.

그래서 Actuator와 Prometheus 그리고 시각화를 도와주는 Grafana를 사용하기로 했습니다.

 

Actuator : 매트릭 정보를 쉽게 제공을 합니다.
Prometheus: 매트릭 정보를 수집 및 저장을 합니다.
Grafana: 수집된 매트릭 정보들을 사용자에게 보기 좋게 대시보드 형태로 제공합니다.

 

 

프로젝트에 적용 전 먼저 빈 프로젝트를 생성하여 로컬에서 확인을 진행을 했습니다.

 

build.gradle

implementation 'org.springframework.boot:spring-boot-starter-actuator'

 

actuator 의존성을 추가합니다.

 

의존성 추가 후 애플리케이션을 실행을 시키면 아래 주소로 접속이 가능합니다.

http://localhost:8080/actuator

 

health와 관련된 파일을 설정을 합니다.

management:
  endpoints:
    web:
      exposure:
        include: "*"

 

테스트용이기에 모든 데이터를 볼 수 있도록 지정합니다.

 

다른 좋은 글이 많기에 간단하게 설명을 하고 제가 겪은 문제에 대해서 말씀드리겠습니다.

저는 Prometheus를 사용하기 위해 직접 설치를 하지 않고 docker에서 image를 pull 받은 후에 사용을 했습니다.

 

docker pull ubuntu/prometheus

 

해당 명령어로 Prometheus 이미지를 받습니다.

docker run -d --name {container-name} -p 9090:9090 ubuntu/prometheus

 

기존에 포트 설정 없이 컨테이너를 실행을 했었는데

http://localhost:9090로 접속이 되지 않았습니다. 그래서 현재 컨테이너를 확인을 해보니 포트 값이 매핑이 되어있지 않았습니다.

저는 그 이유로 되지 않는다고 판단을 하고 컨테이너를 지운 후 다시 실행을 하니 정상적으로 포트 접속이 가능했습니다.

 

이제 어플리케이션에 Prometheus를 사용하기 위해 의존성을 추가 해줍니다.

 

build.gradle

implementation 'io.micrometer:micrometer-registry-prometheus'

 

추가를 한 후 애플리케이션을 실행하게 되면

http://localhost:8080/actuator/prometheus 로 접속이 가능합니다.

 

이제 어플리케이션에서 접속이 가능해졌다면

저희가 사용하는 어플리케이션의 정보를 Prometheus가 수집이 가능하도록 설정을 해야합니다.

 

여기서부터 제가 겪었던 이슈입니다.

 

여러 블로그를 참고를 했지만

prometheus.yml 파일 설정을 변경을 해줘야 된다고 나와 있었습니다.

그래서 prometheus.yml 파일이 도대체 어디에 존재를 하는가 이 문제점에 도달을 했습니다.

분명 제 생각엔 어플리케이션에서 yml 설정을 하는 느낌은 아니였고..

그래서 찾던 도중 직접 설치를 했을 때 로컬에 존재하는 prometheus 폴더 내부에 해당 파일이 존재를 했습니다.

그래서 전 컨테이너로 들어갔습니다.

아래 명령어로 컨테이너의 이름을 찾은 후 접속하시면 됩니다.
docker ps -a
docker exec -it {docker-container-name} /bin/bash

 

해당 명령어를 통해 도커 컨테이너 안으로 접속을 했습니다.

 

컨테이너로 접속을 하게되면 기본적으로 사용을 하던 파일 편집기가 존재 하지 않습니다.

apt update
apt install vim

명령어를 사용하여 vim을 설치를 합니다. (nano, vi 등 편하신 편집기를 사용하시면 됩니다.)

 

컨테이너로 들어가서

cd /etc/prometheus

etc 폴더 내부의 prometheus 폴더로 접속을 하시면 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: "prometheus"

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

    static_configs:
      - targets: ["localhost:9090"]

이후 편집기를 통하여 파일을 열어보면 기본 설정이 되어 있는 것을 알 수 있습니다.

 

이곳에 가장 하단에 저희가 수집하고자 하는 포트와 수집을 요청하는 시간 등 설정을 해줍니다.

 

# 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: "prometheus"

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

    static_configs:
      - targets: ["localhost:9090"]

  - job_name: "spring"
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:8080']

 

이와 같이 yml을 수정을 한 후에 컨테이너에서 나와

docker stop {docker-container-name}
docker start {docker-container-name}

 

컨테이너를 종료 후 다시 실행을 시켜줍니다.

 

그리고 http://localhost:9090/targets 를 접속하여 저희가 설정한 값이 잘 있나 확인했습니다.

 

그런데.. 빨간 글씨를 발견을 하고 말았습니다..

Get "http://localhost:8080/actuator/prometheus": {포트번호}: connect: connection refused

 

연결을 할 수 없다고 나와 있었습니다.. 그리곤 이건 무슨 이유일까 생각을 해보았습니다.

그리곤 로컬 환경에 직접적으로 설치를 한 것이 아니기에 localhost가 아닌가? 라는 생각이 들었습니다.

저는 prometheus에 static_configs에 포트 targets을 localhost:8080으로 하였습니다.

그리고 구글링을 하던 도중 저와 동일한 문제점이 있는 사람들이 꽤 있었습니다.

 - job_name: "spring"
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s
    static_configs:
      - targets: ['localhost:8080']

 

제가 추가를 한 부분에서 도커를 사용하면 설정이 변경이 되어야 합니다.

 - job_name: "{docker-container-name}"
    metrics_path: '/actuator/prometheus'
    scrape_interval: 5s
    static_configs:
      - targets: ['host.docker.internal:8080']

다음과 같이 docker를 사용 했을 때로 설정을 변경을 해야합니다.

이렇게 변경을 하고 아까와 같이 컨테이너를 종료 후 시작을 시키면 http://localhost:9090/targets 접속을 하면

정상적으로 정보를 수집을 할 수가 있습니다.

 

이제 Grafana 설정을 해주려고 합니다.

동일하게 도커를 사용해서 이미지를 받아 컨테이너를 실행 했습니다.

docker pull grafana/grafana
docker run -d --name {container-name} -p 3000:3000 grafana/grafana

 

Grafana도 동일하게 3000 포트로 적용 시켜주지 않으면 실행이 되지 않았기에 포트를 설정을 했습니다.

그리고 컨테이너가 실행이 된다면

http://localhost:3000 으로 접속하면 됩니다.

접속 후 ID/PW 모두 admin 입니다. 입력을 하면 비밀번호 변경 페이지로 이동하며 비밀번호를 따로 설정을 해주면 됩니다.

 

이제 접속을 모두 했다면 좌측 배너에 Data sources를 찾으면 됩니다.

눌러서 들어와 Add new data source를 눌러 Prometheus를 선택합니다.

 

다음과 같이 연결을 할 URL을 입력을 하라고 합니다.

이 부분에서 또.. 문제가 발생을 합니다.

http://localhost:9090은 prometheus의 기본 포트이기에 처음엔 해당 URL을 넣고 가장 아래에 있는 Save&Test를 눌렀습니다. 

Post "http://localhost:9090/api/v1/query": dial tcp 127.0.0.1:9090: connect: connection refused - There was an error returned querying the Prometheus API.

 

그치만 다음과 같이.. 또 연결을 할 수가 없다고 나왔습니다.

그래서 http://localhost:8080으로 해도 되지 않고

http://localhost:8080/actuator/prometheus 를 사용해도 되지 않았습니다.

여기서 또 갑자기 든 생각이 있었습니다.

prometheus를 설정하는 부분과 같이 도커를 사용을 했으니 해당 컨테이너의 IP를 넣어줘야하나?

이런 생각이 들었습니다.

 

docker inspect {docker-container-name}

 

명령어를 사용하여 해당 컨테이너의 IP를 찾아나섰습니다.

명령어를 사용하시고 유심히 보다보면 IPAddress라는 항목이 있습니다.

http://{docker-container-IPAddress}:9090

 

 

이렇게 도커 컨테이너의 IP를 넣어주니

 

 

마법과 같이 성공을 했습니다.

 

아직 로컬에서만 설정을 해봤고 추후에 직접 배포 서버에 연동을 해서 대시보드 설정과 돌아오도록 하겠습니다.

반응형
LIST

'Project > Nuwa' 카테고리의 다른 글

Nuwa Project - S3 Delete File (issue)  (1) 2024.03.08
Nuwa Project - MongoDB 해킹 (issue)  (0) 2024.03.04
Nuwa Project - 문자열 Decode  (1) 2024.02.25
Nuwa Project - Querydsl 정렬  (0) 2024.02.25
Nuwa Project - Querydsl 적용기  (0) 2024.02.24