IT/개발

[Linux][모니터링] Prometheus Agent 설치에서 모니터링 설정까지 #step1

혜인이와함께 2025. 4. 22. 11:27

시스템 모니터링 방법에 대해서 찾아보다가 오픈소스로 활용 가능한 Prometheus 를 이용한 방법을 찾아보고 진행 해보는 과정을 남겨놓기로 했습니다. 

개발해서 운영하는 시스템이 한두개일 때는 큰 부담이 없는데... 

두개 세개...점점 늘어나서 손가락 10개로도 부족해지면 그중에 하나라도 문제가 발생하면 ?

특히나 웹서버 같은 실시간 처리를 위한 서버들이 문제가 발생할때 일반적으로 하나만 문제가 생기지 않고 몰려오는 트래픽에 모든 서버들이 영향을 받게 됨으로 최대한 빨리 인지해서 빠른 조치가 필요합니다.

 

1. Prometheus 구조

 - Exporter

   * 클라이언트의 수집대상에서 수집하려고 하는 타입에 따라 해당하는 타입을 설치한다.
      node (운영 서버의 전반적인 데이터) mysql (DB 의 전반적인 데이터)  등...

 - Server

   * client 에 가지고 있는 데이터를 pull 방식으로 조회한다. 

 - AlertManager

   * Server에서 수집한 데이터를 AlertManager에서 정의한 룰에 따라 알림 기능을 제공한다. 

 - PromQL

   * 매트릭으로 수집된 데이터 수집 타입을 쿼리 형태로 조회할 수 있게 해주는 쿼리언어 

 - Visualization 

   * 시각화 기능을 제공하지만 실시간 조회 라던지 편의 기능은 Grafana 또는 kibana 와 같은 전용 대시보드 툴을 사용해야함.

 

2. 구성 방법

    - 데이터를 저장하여 지난 시간의 통계를 같이 확인할 것인가... ? -> Exporter + Prometheus + AlertManager

    - 데이터 저장 필요없이 그냥 실시간으로 모니터링 하다가 알림 해주고 알림이력은 어차피 모바일 기기와 같은 곳에 남으니까 그걸로 확인하겠다면..? -> Exporter + Grafana 구성으로 가도됨. 

 

3. 구축 (Exporter + Prometheus + AlertManager 을 통한 알림 기능 목표)  

 - Exporter 

    * Metric에 따라 Exporter는 여러개로 나누어 질 수 있음. 
      필요한 모니터링 항목에 따라 Exporter 를 구성하고 Server에서 요청하면 됨.
      참고 : https://prometheus.io/docs/instrumenting/exporters/

 

Exporters and integrations | Prometheus

An open-source monitoring system with a dimensional data model, flexible query language, efficient time series database and modern alerting approach.

prometheus.io

 리눅스 환경에서는 wget 을 통해 필요한 Exporter를 다운로드 받을 수 있다. 

 구축할 때는 node Exporter 를 기반으로 먼저 작성할 예정입니다. 

# 1. 다운로드
wget https://github.com/prometheus/node_exporter/releases/download/v1.9.1/node_exporter-1.9.1.linux-amd64.tar.gz

# 2. 압축 해제
tar -xvzf node_exporter-1.9.1.linux-amd64.tar.gz

# 3. 실행 파일 복사
cp node_exporter-1.9.1.linux-amd64/node_exporter /usr/local/bin/

#systemctl add
vi /etc/systemd/system/node_exporter.service

#service content 
[Unit]
Description=Node Exporter
Wants=network-online.target
After=network-online.target

[Service]
User=root
Group=root
Type=simple
ExecStart=/usr/local/bin/node_exporter \
  --collector.cpu \
  --collector.meminfo \
  --collector.loadavg \
  --collector.diskstats \
  --collector.processes \
  --no-collector.netstat \
  --no-collector.buddyinfo \
  --no-collector.zfs \
  --no-collector.entropy

[Install]
WantedBy=default.target

# 데몬 리로드
systemctl daemon-reexec
systemctl daemon-reload

# 서비스 시작
systemctl start node_exporter

# 부팅 시 자동 시작
systemctl enable node_exporter

# 상태 확인
systemctl status node_exporter

 

 - Prometheus Server

    * PromQL을 통한 질의에 대한 결과를 Metric 서버에 요청함.

     

#!/bin/bash

# 사용할 Prometheus 버전
VERSION="3.3.0"

# 1. 다운로드 및 압축 해제
wget https://github.com/prometheus/prometheus/releases/download/v$VERSION/prometheus-$VERSION.linux-amd64.tar.gz
tar -xvzf prometheus-$VERSION.linux-amd64.tar.gz

# 2. 실행 파일 복사
cp prometheus-$VERSION.linux-amd64/prometheus /usr/local/bin/
cp prometheus-$VERSION.linux-amd64/promtool /usr/local/bin/

# 3. 설정 디렉토리 및 기본 파일 구성
mkdir -p /etc/prometheus
#cp -r prometheus-$VERSION.linux-amd64/consoles /etc/prometheus/
#cp -r prometheus-$VERSION.linux-amd64/console_libraries /etc/prometheus/
cp prometheus-$VERSION.linux-amd64/prometheus.yml /etc/prometheus/

# 4. 데이터 디렉토리 생성
mkdir -p /var/lib/prometheus

# 5. systemd 서비스 유닛 파일 생성
cat <<EOF > /etc/systemd/system/prometheus.service
[Unit]
Description=Prometheus Monitoring
Wants=network-online.target
After=network-online.target

[Service]
User=root
ExecStart=/usr/local/bin/prometheus \\
  --config.file=/etc/prometheus/prometheus.yml \\
  --storage.tsdb.path=/var/lib/prometheus \\
  #--web.console.templates=/etc/prometheus/consoles \\
  #--web.console.libraries=/etc/prometheus/console_libraries
Restart=always

[Install]
WantedBy=multi-user.target
EOF

# 6. 서비스 등록 및 실행
systemctl daemon-reload
systemctl enable prometheus
systemctl start prometheus

# 7. 상태 확인
systemctl status prometheus
echo "✅ Prometheus 설치 및 실행 완료!"
echo "🌐 접속: http://<서버IP>:9090"

 - Node 추가
   * Exporter 대상 서버    

cd /etc/prometheus/prometheus.yml

scrape_configs:
  - job_name: 'node-exporter'
    static_configs:
      - targets: ['192.168.0.101:9100']

   

 - AlertManager 

    * Rule 기반으로 동작하며 Server 에서 수집한 데이터를 기준으로 알림 조건인지 확인 요청하면 AlertManager가 확인 후 알림 발송

#!/bin/bash

# 사용할 Alertmanager 버전
ALERTMANAGER_VERSION="0.28.1"

# 1. Alertmanager 다운로드 및 압축 해제
wget https://github.com/prometheus/alertmanager/releases/download/v$ALERTMANAGER_VERSION/alertmanager-$ALERTMANAGER_VERSION.linux-amd64.tar.gz
tar -xvzf alertmanager-$ALERTMANAGER_VERSION.linux-amd64.tar.gz

# 2. 바이너리 복사
cp alertmanager-$ALERTMANAGER_VERSION.linux-amd64/alertmanager /usr/local/bin/
cp alertmanager-$ALERTMANAGER_VERSION.linux-amd64/amtool /usr/local/bin/

# 3. 설정 디렉토리 구성
mkdir -p /etc/alertmanager
mkdir -p /var/lib/alertmanager

# 4. 기본 알림 설정 작성
vi /etc/alertmanager/alertmanager.yml
global:
  resolve_timeout: 5m

route:
  receiver: 'slack-notifications'

receivers:
  - name: 'slack-notifications'
    slack_configs:
      - send_resolved: true
        username: 'Alertmanager'
        channel: '#채널'
        api_url: 'slack Webhook URL'  # 여기에 본인의 Slack Webhook URL 입력
        title: '{{ .CommonLabels.alertname }}'
        text: >-
          *Alert:* {{ .CommonLabels.alertname }}
          *Status:* {{ .Status }}
          *Instance:* {{ .CommonLabels.instance }}
          *Summary:* {{ .CommonAnnotations.summary }}

# 5. systemd 서비스 등록
cat <<EOF > /etc/systemd/system/alertmanager.service
[Unit]
Description=Alertmanager Service
After=network.target

[Service]
User=root
ExecStart=/usr/local/bin/alertmanager \\
  --config.file=/etc/alertmanager/alertmanager.yml \\
  --storage.path=/var/lib/alertmanager
Restart=on-failure

[Install]
WantedBy=multi-user.target
EOF

# 6. 서비스 등록 및 실행
systemctl daemon-reload
systemctl enable alertmanager
systemctl start alertmanager

# 7. Prometheus에 Alertmanager 연동 설정 추가
PROM_CONFIG="/etc/prometheus/prometheus.yml"
if grep -q "alerting:" "$PROM_CONFIG"; then
  echo "⚠️ Prometheus 설정에 이미 alerting 항목이 존재합니다. 수동 확인 필요!"
else
  echo "🔧 Prometheus 설정에 alerting 항목 추가..."
  cat <<EOC >> "$PROM_CONFIG"

alerting:
  alertmanagers:
    - static_configs:
        - targets:
            - "localhost:9093"
EOC
fi

# 8. Prometheus 재시작
systemctl restart prometheus

# 9. 결과 출력
echo ""
echo "✅ Alertmanager 설치 및 연동 완료!"
echo "🌐 Alertmanager 접속: http://<서버IP>:9093"
echo "🔧 Prometheus 설정 확인: /etc/prometheus/prometheus.yml"
echo "📧 이메일 설정을 바꾸려면 /etc/alertmanager/alertmanager.yml 수정"

   

 - 구축 후에 설정하는 부분은 2차에서 진행하도록 하겠습니다.