- 출처 / 참고: Prometheus Official Documentation (Monitoring Linux host metrics with the Node Exporter, Alerting rules), Grafana Labs Documentation
명령어:
prometheus,node_exporter,promtool,curl,systemctl,ss
키워드: Prometheus, Node Exporter, Grafana, Alertmanager, Time Series Database, Scrape Interval, PromQL, Observability
사용처: 다수의 리눅스 서버, 데이터베이스, 네트워크 장비의 CPU/메모리/디스크 I/O 지표를 중앙 집중 수집하고 임계치 초과 시 실시간 장애 알림 체계 구축
실행예제
인프라 관제 시스템을 구축하거나 기존 에이전트에서 메트릭 수집이 누락될 때, 리눅스 호스트의 Node Exporter 엔드포인트 정상 응답 여부와 Prometheus 서버의 타겟 스크랩(Scrape) 상태 및 설정 파일 문법 무결성을 점검합니다.
# 1. 모니터링 대상 리눅스 서버 관점: Node Exporter 데몬 구동 및 9100 포트 리스닝 확인
$ systemctl status node_exporter
# ● node_exporter.service - Prometheus Node Exporter
# Loaded: loaded (/etc/systemd/system/node_exporter.service; enabled; vendor preset: enabled)
# Active: active (running) since Tue 2026-11-17 09:00:00 KST; 2h 15min ago
$ ss -tulpn | grep :9100
# tcp LISTEN 0 4096 *:9100 *:* users:(("node_exporter",pid=1420,fd=3))
# 2. 로컬에서 Node Exporter 메트릭 정상 노출 여부 직접 테스트
$ curl -s http://localhost:9100/metrics | grep -E "^node_cpu_seconds_total|^node_memory_MemAvailable_bytes" | head -n 6
# node_cpu_seconds_total{cpu="0",mode="idle"} 8421.15
# node_cpu_seconds_total{cpu="0",mode="iowait"} 12.40
# node_memory_MemAvailable_bytes 1.245120512e+10
# -> 커널 지표가 텍스트 포맷으로 정상 출력됨 확인
# 3. 관제 서버(Prometheus) 관점: 설정 파일(prometheus.yml) 및 알림 룰 문법 무결성 검증
$ promtool check config /etc/prometheus/prometheus.yml
# Checking /etc/prometheus/prometheus.yml
# SUCCESS: 1 rule files found
# Checking /etc/prometheus/rules/infra_alerts.yml
# SUCCESS: 8 rules found
# -> 문법 오류로 인한 Prometheus 재시작 실패를 사전에 방지
# 4. Prometheus HTTP API를 이용한 타겟 수집 상태(UP / DOWN) 일괄 조회
$ curl -s http://localhost:9090/api/v1/targets | grep -oE '"instance":"[^"]+","job":"[^"]+"|"health":"[^"]+"'
# "instance":"192.168.1.10:9100","job":"linux_nodes"
# "health":"up"
# "instance":"192.168.1.11:9100","job":"linux_nodes"
# "health":"down"
# -> 192.168.1.11 노드가 방화벽 차단 또는 에이전트 다운으로 수집 실패(down) 상태임 확인
스크립트
리눅스 서버에 Node Exporter를 표준 systemd 데몬으로 자동 설치/배포하고 방화벽(9100 포트) 개방 및 Prometheus 타겟 수집 상태를 검증하는 엔터프라이즈 에이전트 자동 배포 쉘 스크립트입니다.
#!/bin/bash
# deploy_node_exporter.sh - Automated installation and configuration of Prometheus Node Exporter
EXPORTER_VER="1.8.2"
ARCH="linux-amd64"
DOWNLOAD_URL="https://github.com/prometheus/node_exporter/releases/download/v${EXPORTER_VER}/node_exporter-${EXPORTER_VER}.${ARCH}.tar.gz"
echo "=========================================="
echo " [Prometheus Node Exporter 표준 배포 스크립트]"
echo " 설치 버전: v${EXPORTER_VER}"
echo "=========================================="
if [ "$EUID" -ne 0 ]; then
echo " [오류] 시스템 서비스 등록을 위해 루트(root) 권한이 필요합니다."
exit 1
fi
# 1. 전용 시스템 계정 생성 (보안 최소 권한 원칙)
if ! id "node_exporter" &>/dev/null; then
echo -e "\n[1] 전용 서비스 계정(node_exporter) 생성 중..."
useradd --no-create-home --shell /bin/false node_exporter
fi
# 2. 바이너리 다운로드 및 설치
echo -e "\n[2] Node Exporter 바이너리 다운로드 및 배치:"
cd /tmp || exit 1
curl -sLO "$DOWNLOAD_URL"
if [ ! -f "node_exporter-${EXPORTER_VER}.${ARCH}.tar.gz" ]; then
echo " [오류] 다운로드에 실패했습니다. 외부 인터넷 연결 또는 사내 미러 주소를 확인하십시오."
exit 1
fi
tar -xzf "node_exporter-${EXPORTER_VER}.${ARCH}.tar.gz"
cp "node_exporter-${EXPORTER_VER}.${ARCH}/node_exporter" /usr/local/bin/
chown node_exporter:node_exporter /usr/local/bin/node_exporter
rm -rf "node_exporter-${EXPORTER_VER}.${ARCH}"*
echo " - 바이너리 설치 완료: /usr/local/bin/node_exporter"
# 3. systemd 서비스 유닛 파일 생성
# 불필요한 컬렉터 제외 및 systemd 서비스 상태 모니터링 활성화
echo -e "\n[3] systemd 서비스 유닛 등록 중..."
cat << 'EOF' > /etc/systemd/system/node_exporter.service
[Unit]
Description=Prometheus Node Exporter
Wants=network-online.target
After=network-online.target
[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter \
--collector.systemd \
--collector.processes \
--no-collector.wifi \
--no-collector.hwmon
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable --now node_exporter
# 4. OS 방화벽 9100 포트 개방
echo -e "\n[4] OS 방화벽(9100/tcp) 개방 설정:"
if command -v firewall-cmd &>/dev/null && systemctl is-active --quiet firewalld; then
firewall-cmd --permanent --add-port=9100/tcp >/dev/null 2>&1
firewall-cmd --reload >/dev/null 2>&1
echo " - firewalld 9100/tcp 개방 완료"
elif command -v ufw &>/dev/null && ufw status | grep -q "Status: active"; then
ufw allow 9100/tcp >/dev/null 2>&1
echo " - ufw 9100/tcp 개방 완료"
else
echo " - 활성화된 로컬 방화벽이 없거나 수동 iptables 환경입니다."
fi
# 5. 최종 메트릭 응답 검증
echo -e "\n[5] 최종 헬스체크:"
sleep 2
if curl -s http://localhost:9100/metrics | grep -q "node_exporter_build_info"; then
echo " [성공] Node Exporter가 정상 가동 중이며 메트릭을 노출하고 있습니다."
else
echo " [실패] 메트릭 엔드포인트 응답이 없습니다. journalctl -u node_exporter 로그를 확인하십시오."
fi
echo -e "\n=========================================="
echo " [배포 완료]"
echo "=========================================="
해설
장애가 발생한 뒤에 서버에 접속해 top, iostat, dmesg를 치는 것은 사후 대응(Reactive)에 불과합니다. 현대 인프라 운영에서는 Prometheus + Exporter + Grafana + Alertmanager 스택을 통해 수백 대의 서버와 DB 상태를 초 단위로 수집하고, 임계치 도달 전 선제적으로 경보를 울리는 가시성(Observability) 체계를 갖추는 것이 필수적입니다.
1. Pull 기반 아키텍처의 이해
기존 Zabbix나 Nagios의 Push 방식과 달리, Prometheus는 관제 중앙 서버가 주기적으로(보통 15초마다) 각 대상 서버의 HTTP /metrics 엔드포인트를 긁어가는 Pull(Scrape) 모델을 사용합니다.
- 장점: 모니터링 대상 서버에 무거운 에이전트나 DB 드라이버를 깔지 않고 가벼운 바이너리 하나만 띄우면 되며, 대상 서버가 죽었을 때 관제 서버가 즉시
up == 0상태로 다운 여부를 정확히 판별할 수 있습니다.
2. 핵심 인프라 감시 PromQL 쿼리 및 알림 규칙 (infra_alerts.yml)
실무에서 가장 먼저 등록해야 하는 4대 필수 알림 규칙입니다:
groups:
- name: LinuxInfraAlerts
rules:
# 1. 인스턴스 다운 감지 (1분 이상 응답 없음)
- alert: InstanceDown
expr: up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "서버 다운 감지 ()"
# 2. CPU 사용률 90% 초과 지속 (5분 이상)
- alert: HighCpuUsage
expr: 100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[5m])) * 100) > 90
for: 5m
labels:
severity: warning
# 3. 가용 메모리(MemAvailable) 10% 미만 고갈 임박
- alert: LowAvailableMemory
expr: (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100 < 10
for: 3m
labels:
severity: critical
# 4. 루트 및 데이터 파티션 디스크 사용률 90% 초과
- alert: DiskSpaceCritical
expr: 100 - ((node_filesystem_avail_bytes{fstype!~"tmpfs|fuse.lxcfs|squashfs"} * 100) / node_filesystem_size_bytes) > 90
for: 2m
labels:
severity: critical
3. 설정 무중단 반영 (Hot Reload)
Prometheus 설정 파일(prometheus.yml)이나 알림 규칙 파일을 수정한 후 프로세스를 재시작하지 않고 설정만 안전하게 갱신합니다.
# 사전 문법 검사 필수
promtool check config /etc/prometheus/prometheus.yml
# SIGHUP 시그널 전송으로 무중단 리로드
sudo kill -HUP $(pgrep prometheus)
주의사항
- Node Exporter 9100 포트 외부 인터넷 노출 절대 금지:
http://<서버IP>:9100/metrics경로에는 해당 서버의 커널 버전, 마운트 경로, 네트워크 인터페이스 목록, 가동 중인 systemd 서비스 목록 등 민감한 시스템 정보가 인증 없이 평문으로 노출됩니다. 반드시 방화벽이나 클라우드 보안 그룹에서 오직 Prometheus 관제 서버 IP에서만 9100 포트로 접근할 수 있도록 화이트리스트 제한을 걸어야 합니다.
- TSDB 시계열 데이터 보존 주기(
storage.tsdb.retention.time) 설정:- 수백 대의 노드를 15초 간격으로 수집하면 Prometheus 로컬 디스크가 수개월 내로 가득 찰 수 있습니다. 관제 서버의 디스크 용량에 맞추어
--storage.tsdb.retention.time=90d또는 용량 상한(--storage.tsdb.retention.size=200GB)을 반드시 지정해야 디스크 풀로 인한 관제 마비를 방지할 수 있습니다.
- 수백 대의 노드를 15초 간격으로 수집하면 Prometheus 로컬 디스크가 수개월 내로 가득 찰 수 있습니다. 관제 서버의 디스크 용량에 맞추어
- 고카디널리티(High Cardinality) 레이블 남발 주의:
- 커스텀 메트릭을 추가할 때 레이블 값에 사용자 ID, 세션 UUID, 동적 요청 IP처럼 무한대로 늘어나는 값을 넣으면 시계열 인덱스가 폭발하여 Prometheus 서버가 OOM(Out of Memory)으로 다운됩니다. 레이블은 항상 제한된 집합(예:
env="prod",role="db")으로만 설계해야 합니다.
- 커스텀 메트릭을 추가할 때 레이블 값에 사용자 ID, 세션 UUID, 동적 요청 IP처럼 무한대로 늘어나는 값을 넣으면 시계열 인덱스가 폭발하여 Prometheus 서버가 OOM(Out of Memory)으로 다운됩니다. 레이블은 항상 제한된 집합(예: