10.7 외부 모니터링 도구
PostgreSQL의 통계 뷰(10.4)는 SQL 인터페이스지만, 운영에서는 시계열·알람·대시보드가 필요합니다. 외부 모니터링 도구가 이를 채웁니다. Prometheus 기반 표준 스택(postgres_exporter + Grafana)과 대안들을 봅니다.
표준 스택 — Prometheus + postgres_exporter + Grafana
flowchart LR
PG["PostgreSQL"]
EXP["postgres_exporter<br/>(/metrics)"]
PROM["Prometheus<br/>(scrape, store)"]
GRAF["Grafana<br/>(dashboard, alert)"]
ALERT["Alertmanager<br/>→ Slack/Pager"]
PG --> EXP --> PROM --> GRAF
PROM --> ALERT
classDef pg fill:#ede9fe,stroke:#6d28d9,color:#3b0764,stroke-width:2px
classDef exp fill:#dbeafe,stroke:#1d4ed8,color:#1e3a8a
classDef vis fill:#d1fae5,stroke:#047857,color:#064e3b
classDef alert fill:#fed7aa,stroke:#c2410c,color:#7c2d12
class PG pg
class EXP exp
class PROM,GRAF vis
class ALERT alert
postgres_exporter 설치
# RHEL/Rocky 또는 PGDG
sudo dnf install -y postgres_exporter
# 또는 GitHub release에서 바이너리 받음systemd 유닛 (/etc/systemd/system/postgres_exporter.service):
[Service]
User=postgres
Environment=DATA_SOURCE_NAME=postgresql:///?host=/var/run/postgresql&sslmode=disable
ExecStart=/usr/local/bin/postgres_exporter --web.listen-address=:9187
Restart=alwayssudo systemctl enable --now postgres_exporter
curl http://localhost:9187/metrics | headPostgreSQL 측 권한
CREATE ROLE monitoring LOGIN PASSWORD 'secret';
GRANT pg_monitor TO monitoring; -- PG 10+의 통합 권한 (9.1)pg_monitor 역할로 모든 통계 뷰·일부 슈퍼유저 함수 접근 가능합니다. 별도로 LOGIN만 부여하면 됩니다.
Prometheus scrape
prometheus.yml:
scrape_configs:
- job_name: 'postgres'
static_configs:
- targets: ['db1.example.com:9187', 'db2.example.com:9187']
scrape_interval: 30sGrafana 대시보드
grafana.com/dashboards에 PostgreSQL 대시보드가 다수 — 가장 인기 있는 것:
9628PostgreSQL Database (Postgres Exporter)455PostgreSQL Database12273PostgreSQL Overview
대시보드 import 후 datasource를 Prometheus로 지정하면 거의 즉시 사용합니다.
주요 메트릭
postgres_exporter가 노출하는 핵심:
| 메트릭 | 출처 |
|---|---|
pg_up | 연결 가능 여부 |
pg_database_size_bytes | DB 크기 |
pg_stat_database_blks_hit / blks_read | 캐시 hit ratio |
pg_stat_database_xact_commit / rollback | 트랜잭션 |
pg_stat_database_deadlocks | 데드락 수 |
pg_stat_activity_count{state=...} | 상태별 백엔드 수 |
pg_stat_replication_lag | 복제 지연 |
pg_stat_bgwriter_* | 체크포인터·bgwriter |
pg_stat_user_tables_* | 테이블별 row 카운터 |
pg_stat_statements_* | (커스텀 쿼리 필요) |
pg_settings_* | 현재 설정값 |
커스텀 쿼리
기본 exporter가 안 모으는 지표는 queries.yaml에 SQL 정의합니다.
pg_replication_slots:
query: |
SELECT slot_name, slot_type, active::int,
pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) AS lag_bytes
FROM pg_replication_slots;
metrics:
- slot_name: { usage: LABEL }
- slot_type: { usage: LABEL }
- active: { usage: GAUGE, description: "Slot active 여부" }
- lag_bytes: { usage: GAUGE, description: "WAL 지연 바이트" }postgres_exporter --extend.query-path=/etc/postgres_exporter/queries.yaml로 로딩.
알람 — Alertmanager / Grafana
기본 알람 룰 (Prometheus 룰 파일):
groups:
- name: postgres
rules:
- alert: PostgresDown
expr: pg_up == 0
for: 1m
annotations:
summary: "PostgreSQL down"
- alert: ReplicationLagHigh
expr: pg_replication_lag > 100*1024*1024 # 100MB
for: 5m
- alert: LongRunningTransaction
expr: pg_stat_activity_max_tx_duration{state="active"} > 300
for: 1m8.4의 점검 임계와 맞추면 운영 표준이 만들어집니다.
대안 — pgwatch2
EnterpriseDB가 유지보수하는 통합 모니터링 도구입니다. exporter·DB·UI를 한 묶음으로 제공합니다.
docker run -d --name pgwatch2 \
-p 3000:3000 -p 8080:8080 \
-e PW2_TESTDB=true \
cybertec/pgwatch2:latest장점: 설치 빠름, 대시보드 풍부. 단점: Prometheus 표준 스택과 분리합니다.
대안 — Datadog
# datadog agent의 postgres integration
cat << EOF > /etc/datadog-agent/conf.d/postgres.d/conf.yaml
init_config:
instances:
- host: localhost
port: 5432
username: datadog
password: secret
dbm: true # Database Monitoring 활성
EOF상용 도구지만 쿼리 분석·트레이스 통합이 강력. 마이크로서비스 환경에서 흔히 채택.
대안 — pganalyze / Datadog DBM / Crunchy Bridge / pgEdge
SaaS 또는 매니지드 형태. pg_stat_statements·auto_explain 로그를 자동 수집·시각화. 비용 들지만 설치·운영 부담 적습니다.
| 도구 | 라이선스 | 강점 |
|---|---|---|
| pganalyze | 상용 SaaS | 쿼리 분석·인덱스 권장 |
| Datadog DBM | 상용 SaaS | APM 통합 |
| Cybertec PG Watch | 무료/유료 | 자체 호스팅 |
| AWS CloudWatch | RDS 통합 | 매니지드 환경 표준 |
| Azure Database Insights | Azure 통합 | 같음 |
매니지드 클라우드의 자체 도구
| 클라우드 | 모니터링 |
|---|---|
| AWS RDS | Performance Insights + CloudWatch |
| Azure Database for PostgreSQL | Query Performance Insight + Azure Monitor |
| GCP Cloud SQL | Query Insights + Cloud Monitoring |
| NCP Cloud DB for PostgreSQL | NCP 모니터링 통합 |
매니지드는 보통 자체 도구로 충분 — postgres_exporter 추가 설치가 불필요한 경우 많습니다.
운영 권장 아키텍처
| 환경 | 권장 |
|---|---|
| 셀프 호스팅 1~10대 | postgres_exporter + Prometheus + Grafana |
| 셀프 호스팅 수십~수백 대 | + pganalyze 또는 Datadog DBM 검토 |
| 매니지드 | 클라우드 자체 도구 |
| 컴플라이언스 강한 환경 | 자체 호스팅 + 외부 노출 차단 |
운영 안티패턴
| 안티패턴 | 위험 |
|---|---|
| 모니터링 사용자가 슈퍼유저 | 보안 — pg_monitor 사용 |
pg_stat_statements_reset()을 외부 도구가 호출 | 다른 도구의 추세 분석 깨짐 |
| scrape_interval = 5초 | 비용·부하 — 30~60초 권장 |
| 알람 없이 대시보드만 | 새벽 사고 못 잡음 |
| 알람 임계가 너무 빡빡 | 알람 피로 → 진짜 알람 무시 |
정리
- 표준 스택: postgres_exporter + Prometheus + Grafana + Alertmanager
- 모니터링 사용자는
pg_monitor역할로 충분 — 슈퍼유저 금지 - 기본 metric 외에 커스텀 쿼리로 보강
- pgwatch2·Datadog DBM·pganalyze 같은 통합 도구도 대안
- 매니지드는 클라우드 자체 도구가 보통 답
- scrape_interval은 30~60초, 알람 임계는 8.4와 정렬
다음 절(10.8)에서는 PostgreSQL 외부 — OS 메트릭(node_exporter, iostat 등) 연동을 봅니다.