Prometheus 배포
Prometheus와 Grafana를 통한 모니터링 시스템 구축은 현대 인프라 관리에 필수적입니다. 이 과정에서 특히 이미지 패키지와 CPU 아키텍처 간의 호환성에 주의해야 합니다.
배치 환경 정보:
- macOS 장비
- Prometheus 버전 3.4.0
- Grafana 버전 12.0.1
바이너리 패키지 설치 방법
1. 다운로드 및 설치
먼저 구성 파일을 저장할 디렉토리를 생성합니다:
mkdir prometheus-grafana
cd prometheus-grafana
CPU 아키텍처에 맞는 Prometheus 설치 패키지를 다운로드합니다:
wget https://github.com/prometheus/prometheus/releases/download/v3.4.0/prometheus-3.4.0.darwin-arm64.tar.gz
압축을 해제하고 적절한 위치로 이동합니다:
tar xvfz prometheus-3.4.0.darwin-arm64.tar.gz
mv prometheus-3.4.0.darwin-arm64 prometheus-3.4.0
cd prometheus-3.4.0
도움말 정보를 확인합니다:
./prometheus --help
macOS 보안 설정에서 실행 권한을 허용해야 합니다:
- "시스설정" > "개인정보 보호 및 보안" > "보안" 탭에서 해당 애플리케이션에 대한 실행 권한을 "여전히 허용"으로 설정합니다.
2. Prometheus 구성 파일
Prometheus를 시작하기 전에 구성을 설정합니다. Prometheus 구성은 YAML 형식입니다. 압축 해제된 패키지에는 prometheus.yml이라는 예제 구성 파일이 포함되어 있습니다:
# 글로벌 설정
global:
scrape_interval: 15s # 15초마다 데이터 수집 (기본값은 1분)
evaluation_interval: 15s # 15초마다 규칙 평가 (기본값은 1분)
# scrape_timeout은 글로벌 기본값(10s)을 사용합니다.
# 알림 관리자 설정
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# 규칙 파일 로드
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"
# 수집 대상 설정
scrape_configs:
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]
labels:
app: "prometheus"
구성 파일에는 global, alerting, rule_files, scrape_configs 네 가지 주요 섹션이 있습니다.
global섹션은 Prometheus 서버의 전역 설정을 제어합니다.scrape_interval옵션은 Prometheus가 대상에서 데이터를 수집하는 빈도를 제어합니다.evaluation_interval옵션은 Prometheus가 규칙을 평가하는 빈도를 제어합니다.scrape_configs섹션은 Prometheus가 어떤 리소스를 모니터링할지 제어합니다.
prometheus.yml 파일 편집:
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
# - "first.rules"
# - "second.rules"
scrape_configs:
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]
labels:
app: "prometheus"
3. Prometheus 시작
구성 파일을 사용하여 Prometheus를 시작합니다:
./prometheus --config.file=prometheus.yml
시작 후 http://localhost:9090에서 Prometheus UI에 접근할 수 있습니다. 약 30초 정도 기다리면 자체 HTTP 메트릭 엔드포인트에서 데이터를 수집하기 시작합니다. Prometheus가 자체 메트릭을 제공하는지 확인하려면 http://localhost:9090/metrics를 방문합니다.
컨테이너를 통한 설치 방법
prometheus.yml 파일 준비
시작 전에 prometheus.yml 파일을 현재 디렉토리에 준비합니다:
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
# - "first.rules"
# - "second.rules"
scrape_configs:
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]
labels:
app: "prometheus"
Prometheus 컨테이너 실행
docker run -d \
--name prometheus \
-p 9090:9090 \
-v $(pwd)/prometheus.yml:/etc/prometheus/prometheus.yml \
-v prometheus-data:/prometheus \
prom/prometheus \
--config.file=/etc/prometheus/prometheus.yml \
--storage.tsdb.path=/prometheus \
--web.enable-lifecycle
매개변수 설명:
-v prometheus-data:/prometheus: 시계열 데이터를 저장하기 위한 볼륨을 생성하여 컨테이너 재시작 후 데이터 손실을 방지합니다.--web.enable-lifecycle: HTTP 요청을 통해 동적으로 구성을 다시 로드할 수 있도록 허용합니다(컨테이너 재시작 불필요).curl -X POST http://localhost:9090/-/reload명령으로 구성 다시 로드를 트리거할 수 있습니다.
Prometheus 메트릭
http://localhost:9090/metrics에서 Prometheus 메트릭을 확인할 수 있습니다. 메트릭에 대한 자세한 설명은 다음 링크를 참조하세요: Prometheus 메트릭 이해
Node Exporter를 사용한 로컬 호스트 데이터 수집
다운로드 및 설치
Node Exporter 다운로드 링크에서 CPU 아키텍처에 맞는 패키지를 선택합니다:
wget https://github.com/prometheus/node_exporter/releases/download/v1.9.1/node_exporter-1.9.1.darwin-arm64.tar.gz
tar -xzf node_exporter-1.9.1.darwin-arm64.tar.gz
mv node_exporter-1.9.1.darwin-arm64 node_exporter-1.9.1
Node Exporter 시작
cd node_exporter-1.9.1
./node_exporter
Node Exporter가 실행 중이며 9100 포트에서 메트릭을 노출하고 있다는 출력을 볼 수 있습니다:
time=2025-05-28T09:03:49.896Z level=INFO source=node_exporter.go:216 msg="Starting node_exporter" version="(version=1.9.1, branch=HEAD, revision=f2ec547b49af53815038a50265aa2adcd1275959)"
...
time=2025-05-05T09:03:49.897Z level=INFO source=tls_config.go:350 msg="TLS is disabled." http2=false address=[::]:9100
cURL을 사용하여 /metrics 엔드포인트에 접근하여 수집된 데이터를 확인할 수 있습니다:
curl http://localhost:9100/metrics
또는 브라우저에서 http://localhost:9100/metrics를 열어 확인합니다.
Prometheus에서 Node Exporter 모니터링 구성
로컬에서 실행 중인 Prometheus 인스턴스가 Node Exporter 메트릭에 접근하도록 올바르게 구성해야 합니다. prometheus.yml 구성에 다음과 같이 Node Exporter 모니터링 작업을 추가합니다:
scrape_configs:
- job_name: "node"
static_configs:
- targets: ["localhost:9100"]
매개변수 설명:
job_name: "node": 모니터링 대상을 식별하는 데 사용되는 작업 이름입니다.static_configs: 모니터링할 엔드포인트 주소를 직접 지정합니다.targets: ["localhost:9100"]: Node Exporter가 기본적으로 수신하는 주소와 포트입니다.
완전한 prometheus.yml 예제:
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
# - "first.rules"
# - "second.rules"
scrape_configs:
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]
labels:
app: "prometheus"
- job_name: "node"
static_configs:
- targets: ["localhost:9100"]
Prometheus를 다시 시작합니다:
./prometheus --config.file=prometheus.yml
검증
- Prometheus: http://localhost:9090에 접속하고 "up"을 입력한 후 실행 버튼을 클릭하면 다음과 같은 결과를 볼 수 있습니다:
up{instance="localhost:9090",job="prometheus"} 1
up{instance="localhost:9100",job="node"} 1
여기서 "1"은 정상을 의미하며, "0"은 비정상을 의미합니다.
주요 메트릭 예시
| 메트릭 | 의미 |
|---|---|
rate(node_cpu_seconds_total{mode="system"}[1m]) |
지난 1분간 시스템 모드에서 CPU가 초당 평균으로 사용한 시간(초) |
node_filesystem_avail_bytes |
non-root 사용자가 사용할 수 있는 파일 시스템 공간(바이트) |
rate(node_network_receive_bytes_total[1m]) |
지난 1분간 초당 평균 수신 네트워크 트래픽(바이트) |
MySQL Exporter를 사용한 MySQL 데이터 수집
Docker로 MySQL 시작
docker run -d \
--name mysql-server \
-p 3306:3306 \
-p 9104:9104 \
-e MYSQL_DATABASE=test \
-e MYSQL_ROOT_PASSWORD=test \
-e MYSQL_USER=test \
-e MYSQL_PASSWORD=test \
mysql:8.0
MySQL Exporter 다운로드
CPU 아키텍처를 확인합니다:
uname -m # x86_64 또는 aarch64 반환
GitHub에서 해당 아키텍처 버전을 다운로드합니다:
wget https://github.com/prometheus/mysqld_exporter/releases/download/v0.17.2/mysqld_exporter-0.17.2.linux-arm64.tar.gz
지정된 디렉토리로 압축 해제
tar xf mysqld_exporter-0.17.2.linux-arm64.tar.gz -C /usr/local/
cd /usr/local
mv mysqld_exporter-0.17.2.linux-arm64 mysqld_exporter
cd mysqld_exporter
최소 권한 설정 (모범 사례)
데이터 수집을 위한 전용 사용자를 생성합니다:
mysql -u root -p
CREATE USER 'repl_monitor'@'%' IDENTIFIED BY '123456';
GRANT REPLICATION CLIENT ON *.* TO 'repl_monitor'@'%';
GRANT SHOW DATABASES ON *.* TO 'repl_monitor'@'%';
GRANT PROCESS ON *.* TO 'repl_monitor'@'%';
FLUSH PRIVILEGES;
- 주기적인 비밀번호 변경: 수집 사용자에 대한 정기적인 비밀번호 변경 정책을 설정합니다.
구성 파일 생성
cat > .my.cnf << EOF
[client]
user=repl_monitor
password=123456
host=localhost
EOF
chmod 600 .my.cnf
시작 스크립트 생성
cat > /usr/local/mysqld_exporter/run.sh << EOF
#!/bin/bash
/usr/local/mysqld_exporter/mysqld_exporter --config.my-cnf=/usr/local/mysqld_exporter/.my.cnf --web.listen-address=:9104
EOF
chmod +x /usr/local/mysqld_exporter/run.sh
백그라운드로 실행:
nohup /usr/local/mysqld_exporter/run.sh &
Exporter 정상 작동 확인
http://localhost:9104/metrics에 접속하면 MySQL 관련 메트릭이 표시되어야 합니다.
Prometheus에 MySQL 모니터링 항목 추가
Prometheus 구성 파일 prometheus.yml에 MySQL Exporter 수집 작업을 추가합니다:
scrape_configs:
- job_name: "mysql"
static_configs:
- targets: ["localhost:9104"]
완전한 prometheus.yml 예제:
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
# - "first.rules"
# - "second.rules"
scrape_configs:
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]
labels:
app: "prometheus"
- job_name: "node"
static_configs:
- targets: ["localhost:9100"]
- job_name: "mysql"
static_configs:
- targets: ["localhost:9104"]
파일 기반 서비스 검색 방식으로 모니터링 항목 추가
다양한 유형의 서비스(호스트, 데이터베이스, 애플리케이션)를 별도의 job_name으로 분리하는 것이 좋습니다:
targets_mysql.yml:
- targets: ["localhost:9104"]
labels:
app: "mysql_server"
host_type: "container"
targets_node.yml:
- targets: ["localhost:9100"]
labels:
app: "localhost"
host_type: "physical"
prometheus.yml 파일을 수정하여 이러한 대상 목록 파일을 참조합니다:
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]
labels:
app: "prometheus"
- job_name: "node_exporter"
file_sd_configs:
- files:
- "targets_node.yml"
refresh_interval: 1m
- job_name: "mysql_exporter"
file_sd_configs:
- files:
- "targets_mysql.yml"
refresh_interval: 1m
Prometheus를 시작하여 효과를 확인합니다:
./prometheus --config.file=prometheus.yml
Grafana에 MySQL 데이터 소스 추가
Grafana가 올바르게 구성되어 있다는 전제하에, 다음 단계를 따릅니다(여기서는 test 데이터베이스에 접근 권한이 있는 test 사용자 사용):
대시보드에 MySQL 그래프 템플릿 가져오기
https://grafana.com/grafana/dashboards/14057-mysql/ 템플릿을 사용하며, ID 14057을 입력합니다.
Grafana를 사용한 시각화 대시보드 생성
Prometheus UI는 빠른 PromQL 확인 및 임시 시각화 지원을 제공하지만, 대부분의 시나리오에서 장기적으로 사용할 수 있는 모니터링 데이터 시각화 패널(Dashboard)이 필요합니다. 이 경우 Grafana와 같은 타사 시각화 도구를 사용할 수 있으며, Grafana는 Prometheus에 대한 완전한 지원을 제공합니다.
macOS에 Grafana 설치
brew update
brew install grafana
brew services start grafana
서비스 상태 확인:
brew services list
lsof -i :3000
서비스 시작/중지/재시작:
brew services start grafana
brew services stop grafana
brew services restart grafana
Grafana 대시보드 구성
http://localhost:3000/login에 접속합니다.
기본 자격 증명:
사용자 이름: admin
비밀번호: admin
시간대 설정:
- 우측 상단 프로필 아이콘 > Preferences > Timezone에서 원하는 시간대를 선택합니다.
Prometheus를 기본 데이터 소스로 추가:
- Configuration > Data Sources > Add data source
- 데이터 소스 유형으로 Prometheus 선택
- Prometheus 주소 설정 (http://localhost:9090)
- "Add" 버튼 클릭 및 연결 성공 확인
템플릿 가져오기:
- Dashboards > Import
- 템플릿 ID 입력 (예: 1860)
- "Load" 버튼 클릭
Grafana를 한국어로 설정:
- 우측 상단 프로필 아이콘 > Profile
- Language 드롭다운에서 "한국어" 선택
- Save preferences 클릭
Grafana 모니터링 메트릭
http://localhost:3000/metrics에서 Grafana 메트릭을 확인할 수 있습니다.
Grafana 경고 규칙 구성
웹훅 생성하여 경고 정보 수신:
온라인 웹훅 주소: https://webhook.site/를 사용하여 테스트 후 웹훅 구성을 저장합니다.
수동 경고 규칙 생성
Grafana에서 Alerting > Alert rules로 이동합니다. "+ New alert rule" 클릭
경고 규칙 이름을 입력합니다(예: promhttp-code200-requests). 이 이름은 경고 알림에 표시되므로 간결하고 설명적이어야 합니다.
여기서는 promhttp_metric_handler_requests_total{code="200"}의 통계 횟수를 사용하여 경고를 시뮬레이션합니다.
**"Save rule and exit"**를 클릭하여 규칙을 저장합니다. "Firing" 상태는 규칙이 트리거되어 경고가 발생했음을 의미합니다.
대시보드를 통한 경고 규칙 생성
모니터링 패널에서 해당 메트릭의 드롭다운 버튼 > New alert rule을 선택합니다.
폴더 라벨 추가: 폴더 라벨을 사용하여 경고 규칙을 정리합니다.
평가 그룹 정의: 평가 그룹은 경고 및 기록 규칙을 평가하는 컨테이너입니다. 평가 그룹은 규칙 평가 빈도를 정의하는 평가 간격을 정의합니다. 동일한 평가 그룹 내의 경고 규칙은 동일한 평가 간격으로 평가됩니다.
규칙 저장: 몇 분 후 설정된 값(12)을 초과하는 부하가 감지됩니다.
경고가 트리거되었으며, 웹훅에서 경고 정보를 받았습니다.
웹훅 경고 방식을 기본 방식으로 구성합니다.
사용자 정의 경고 메시지: 저장 후 경고 규칙을 클릭하면 규칙 세부 정보를 볼 수 있습니다.