Notice
Recent Posts
Recent Comments
Link
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

JustDoEat

prometheus, telegraf 설정 본문

카테고리 없음

prometheus, telegraf 설정

kingmusung 2024. 1. 24. 21:27

프로메테우스와 telegraf로 메트릭을 수집하고 프로메테우스에 연동이 다 되었는지 확인을 해보려고 합니다.

 

primetheus란?

프로메테우스는 오픈 소스 시스템 모니터링 도구로, 서버, 애플리케이션, 시스템 등에서 성능과 상태에 관한 데이터를 수집하고 분석합니다. 이 데이터는 다차원 데이터 모델을 기반으로 하며, 강력한 쿼리 언어를 사용하여 정보를 추출할 수 있습니다. 프로메테우스는 주기적으로 타겟 시스템에서 지표를 수집하고, 필요에 따라 알림을 생성하여 문제를 신속하게 감지하고 대응할 수 있도록 도와줍니다

 

설정

docker-compose.yml

prometheus:
  container_name: prometheus  # Prometheus 컨테이너의 이름
  image: prom/prometheus  # 사용할 Prometheus 도커 이미지
  restart: 'always'  # 컨테이너가 종료되면 항상 재시작
  volumes:
    - ./prometheus:/etc/prometheus  # 호스트의 ./prometheus 디렉토리를 컨테이너의 /etc/prometheus 디렉토리로 마운트
    - ./prometheus/prometheus.yml:/prometheus/prometheus.yml:ro  # 호스트의 Prometheus 설정 파일을 컨테이너 내의 해당 경로로 마운트 (읽기 전용)
  ports:
    - 9090:9090  # 호스트의 9090 포트를 컨테이너의 9090 포트로 포워딩
  command:
    - '--web.enable-lifecycle'  # Prometheus 웹 인터페이스의 생애주기 지원 활성화
    - '--config.file=/etc/prometheus/prometheus.yml'  # Prometheus 설정 파일의 경로 지정
  networks:
    - haru  # "haru"라는 이름의 도커 네트워크에 연결

config.settings.py

MIDDLEWARE = [
    #기존 코드 생략
    
 
    'django_prometheus.middleware.PrometheusBeforeMiddleware',
    'django_prometheus.middleware.PrometheusAfterMiddleware',

]

 'django_prometheus.middleware.PrometheusBeforeMiddleware'

이 미들웨어는 https요청이 오면 어떤 요청이 왔는지에 대한 정보를 메트릭으로 기록해주는 친구

 

'django_prometheus.middleware.PrometheusAfterMiddleware',

이 미들웨어는 https응답에 대한 메트릭을 수집하는 친구

 

미들웨어란?

쉽게 이야기 하면, 클라이언트가 api요청을 보내면 바로 api로 요청이 가는것이 아니라, middleware라는 곳을 들려 미들웨어의 코드를 "순차적"으로 실행을 한 후 통과가 되면 api로 요청이 전달이 된다. 


config.urls.py

urlpatterns = [
	#기존 경로
    path('', include("django_prometheus.urls")),

]

promethus.yml

global:
  scrape_interval: 15s # 모든 타겟을 15초 간격으로 스크래이핑합니다. 기본값은 1분입니다.
  evaluation_interval: 15s # 전역 'evaluation_interval'에 따라 규칙을 15초마다 평가합니다. 기본값은 1분입니다.

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
# 규칙을 한 번 로드하고 전역 'evaluation_interval'에 따라 주기적으로 평가합니다.
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"

scrape_configs:
  - job_name: "django"
    metrics_path: /metrics
    static_configs:
      - targets:
          - host.docker.internal:8000
    # "django" job에 대한 설정입니다.
    # /metrics 경로에서 메트릭을 수집하고, host.docker.internal:8000에서 데이터를 수집합니다.

#  - job_name: "nginx-prometheus-exporter"
#    metrics_path: /metrics
#    static_configs:
#      - targets: ['nginx-prometheus-exporter:9113']
# "nginx-prometheus-exporter" job에 대한 설정입니다. 주석 처리되어 있어 비활성화되어 있습니다.

  - job_name: 'telegraf'
    static_configs:
      - targets: ['telegraf:9273']
    # "telegraf" job에 대한 설정입니다.
    # telegraf:9273에서 데이터를 수집합니다.

 

scrape_configs:
  - job_name: "django"
    metrics_path: /metrics
    static_configs:
      - targets:
          - host.docker.internal:8000

쉽게 설명하자면.

host.docker.internal:8000 이라는 도커 내부에 컨테이너에 8000번 포트로 입장 후 /metric이라는 엔드 포인트에서 메트릭을 가지고 오라는 말.

 

scrape_config(스크레이프는 데이터를 추출하거나 수집하는 행위를 말함.)

static_config(static은 정적이라는 뜻처럼, 변하지않는 고정값을 설정한다는 의미)

 

메트릭이란?

소프트웨어의 상태나 지표를 나타내주는 지표

http_requests_total과 같이 HTTP 요청의 총 횟수를 나타내는 메트릭 그리고

http_requests_total{method="GET", status="200"}과 같이 특정 HTTP 메서드와 상태 코드에 대한 메트릭을 식별하는 레이블이 있다.

- job_name: 'telegraf'
  static_configs:
    - targets: ['telegraf:9273']

 

이 부분은 아래 telegraf를 설명하면서 추가로 이어가도록 하겠다.


telegraf란

경량 데이터 수집기로서, ELK에서 다룬 filebeat, logstash랑 비슷한 역할을 한다, 즉 데이터를 수집 후 elasticsearch, prometheus같은 DB에 출력값으로써 데이터를 넘겨준다. 나느 데이터를 prometheus로 넘겨줄것이다.

현제 telegraf를 사용하는 이유는

cpu사용량, 메모리사용량, 네트워크 트레픽, 시스템 부하를 확인하기 위해 사용했다.


설정

prometheus.yml

- job_name: 'telegraf'
  static_configs:
    - targets: ['telegraf:9273']
  # "telegraf" job에 대한 설정입니다.
  # telegraf:9273에서 데이터를 수집합니다.

 

사용하기 앞서 prometheus.yml 파일에 위 처럼 적어준다.

telegraf:9273 이라는 타겟으로 가서 메트릭을 수집하라는 뜻이다.

 

docker-compose.yml

#생략
telegraf:
  image: telegraf:latest
  container_name: telegraf
  volumes:
    - ./telegraf.conf:/etc/telegraf/telegraf.conf:ro
  networks:
    - haru
  depends_on:
    - prometheus
  restart: always
  command: [ "telegraf", "--config", "/etc/telegraf/telegraf.conf" ]
#생략

 

 

프로메테우스에 연동이 되었는지 확인하기.

 


프로메테우스 컨테이너의 주소를 눌러주고 http://localhost:9090/ 로 접속

 

status -> target을 눌러주면 위와 같은 화면이 뜨는데, 지금까지 설정했던 target들이 잘 나오는걸 볼 수 있다.

 

state가 초록색으로 되어있으면 성공적으로 연동이 되어있다.

 

보통 여기서 grafana까지 실행을 시켜서 데쉬보드에 이쁘게 나오게 하는게 일반적인 방법이다.

 

다음글에 이어서 진행하도록 하겠다.