7단계
7단계 — 헬스체크·관측
25 분
7단계 — 헬스체크·관측
서버는 살아 있어야 가치가 있어요. 그리고 살아 있는지 누가 어떻게 알지 결정하는 게 관측(observability).
헬스체크 엔드포인트
# routers/health.py
from fastapi import APIRouter, status
from db.connection import get_conn
router = APIRouter()
@router.get("/health")
def health():
return {"status": "ok"}
@router.get("/health/db")
def health_db():
try:
with get_conn() as conn, conn.cursor() as cur:
cur.execute("SELECT 1")
cur.fetchone()
return {"db": "ok"}
except Exception as e:
return {"db": "down", "error": str(e)}, status.HTTP_503_SERVICE_UNAVAILABLE
/health 는 앱이 응답하는지, /health/db 는 DB 까지 연결되는지. 모니터링 시스템이 5분마다 호출.
Docker HEALTHCHECK
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
이 한 줄로 docker-compose 가 건강한 컨테이너만 의존성에 포함시켜요.
구조화 로깅
import logging
import json
class JsonFormatter(logging.Formatter):
def format(self, record):
return json.dumps({
"ts": self.formatTime(record),
"level": record.levelname,
"msg": record.getMessage(),
"module": record.module,
}, ensure_ascii=False)
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logging.getLogger().addHandler(handler)
JSON 으로 로그를 남기면 Loki·CloudWatch·Datadog 같은 도구가 자동 파싱·검색.
메트릭 — Prometheus
from prometheus_client import Counter, Histogram, generate_latest
requests_total = Counter("http_requests_total", "총 HTTP 요청 수", ["method", "path"])
request_duration = Histogram("http_request_duration_seconds", "HTTP 요청 시간")
@router.get("/metrics")
def metrics():
return Response(generate_latest(), media_type="text/plain")
Grafana 가 /metrics 를 1분마다 긁어가 그래프로.
알림 — 무엇이 깨지면 누구에게
세 가지만 정해 두면 절반은 됩니다.
- 무엇 — DB 연결 실패 / 5xx 에러율 > 1% / 메모리 > 80%
- 누구 — Slack 채널 또는 이메일
- 언제 깨움 — 평일 09~18 만 / 24/7
직접 해 보기
/health + /health/db 두 엔드포인트를 추가하고 Dockerfile 에 HEALTHCHECK 를 넣어 보세요. docker compose ps 했을 때 STATUS 가 healthy 면 성공.
더 깊이
다음 단계
이 강좌는 끝났어요. 다음으로 devops-cloud 에서 진짜 클라우드에 올리거나, ai-agent-tooling 에서 AI 도구를 다루는 법을 만나 보세요.
🎉 Python · FastAPI · 데이터 파이프라인 완주를 축하해요
이어서 어떤 걸 배워 볼까요?