티스토리 뷰
📌 NestJS + Kubernetes & 마이크로서비스 배포: 실전 가이드 - NestJS 자동 복구 시스템 구축 – 장애 대응과 모니터링 전략
octo54 2025. 5. 19. 10:02📌 NestJS + Kubernetes & 마이크로서비스 배포: 실전 가이드
29. NestJS 자동 복구 시스템 구축 – 장애 대응과 모니터링 전략
대규모 SaaS 서비스 운영 시 서버 장애와 성능 저하는 피할 수 없는 문제입니다.
NestJS 애플리케이션이 자동으로 복구하고, 문제가 발생했을 때 빠르게 감지하고 대응할 수 있는 구조를 갖추는 것이 중요합니다.
이번 글에서는 NestJS 기반의 자동 복구 시스템 설계와 장애 대응 전략을 소개합니다. 🚑
✅ 1. 장애 발생 시 자동 복구가 필요한 이유
문제점 설명
서버 다운 | 클러스터 내 한 인스턴스가 응답하지 않음 |
메모리 누수 | 장기 실행으로 인해 메모리 부족 |
네트워크 오류 | 외부 API 호출 실패 또는 타임아웃 |
애플리케이션 오류 | 미처리 예외로 인해 서버 프로세스 중단 |
✅ 2. 장애 감지 모니터링 설정
📦 필수 패키지 설치
npm install @nestjs/terminus
📂 헬스 체크 모듈 구성
📂 health/health.module.ts
import { Module } from '@nestjs/common';
import { TerminusModule } from '@nestjs/terminus';
import { HealthController } from './health.controller';
@Module({
imports: [TerminusModule],
controllers: [HealthController],
})
export class HealthModule {}
📂 헬스 체크 컨트롤러
📂 health/health.controller.ts
import { Controller, Get } from '@nestjs/common';
import { HealthCheckService, HttpHealthIndicator } from '@nestjs/terminus';
@Controller('health')
export class HealthController {
constructor(
private health: HealthCheckService,
private http: HttpHealthIndicator,
) {}
@Get()
healthCheck() {
return this.health.check([
() => this.http.pingCheck('nestjs-docs', 'https://docs.nestjs.com'),
]);
}
}
✅ 3. Kubernetes 기반 자동 복구 설정
📦 Deployment 설정 (Liveness & Readiness Probe)
📂 k8s/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nestjs-app
spec:
replicas: 3
template:
metadata:
labels:
app: nestjs-app
spec:
containers:
- name: nestjs-app
image: your-docker-image
ports:
- containerPort: 3000
livenessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 10
periodSeconds: 15
readinessProbe:
httpGet:
path: /health
port: 3000
initialDelaySeconds: 5
periodSeconds: 10
💡 Liveness Probe: 애플리케이션이 살아 있는지 확인
💡 Readiness Probe: 애플리케이션이 요청을 받을 준비가 되었는지 확인
✅ 4. PM2로 프로세스 관리
📦 PM2 설치
npm install pm2 -g
📂 PM2 설정 파일
📂 ecosystem.config.js
module.exports = {
apps: [
{
name: 'nestjs-app',
script: 'dist/main.js',
instances: 'max',
exec_mode: 'cluster',
watch: true,
autorestart: true,
max_memory_restart: '500M',
},
],
};
📦 실행 명령어
pm2 start ecosystem.config.js
✅ 메모리 사용량이 500MB를 넘으면 자동으로 재시작하여 메모리 누수를 방지합니다.
✅ 5. 장애 발생 시 대응 전략
상황 대응 방안
메모리 부족 | 메모리 사용 모니터링, 최대 메모리 설정 |
외부 API 실패 | 타임아웃과 재시도 로직 추가, Circuit Breaker 사용 |
서버 프로세스 중단 | PM2 클러스터 모드로 자동 복구 |
디스크 용량 부족 | 로그 파일 순환 설정 (Log Rotation) |
✅ 6. Circuit Breaker 패턴 적용
📦 패키지 설치
npm install opossum
📂 Circuit Breaker 구현
📂 circuit/circuit.service.ts
import * as CircuitBreaker from 'opossum';
export class CircuitService {
private breaker;
constructor() {
this.breaker = new CircuitBreaker(this.request, {
timeout: 3000,
errorThresholdPercentage: 50,
resetTimeout: 10000,
});
this.breaker.fallback(() => 'Service Unavailable');
}
async request() {
// 외부 API 요청
const response = await fetch('https://external-api.com');
if (!response.ok) throw new Error('Request failed');
return response.json();
}
async getData() {
return this.breaker.fire();
}
}
✅ 7. 장애 탐지와 알림 시스템
📦 Grafana Alert 설정
- 대시보드 패널에서 Edit 클릭
- Alert 탭 선택
- 조건 설정: HTTP 응답 속도가 1초 이상이면 경고
- 알림 채널 설정: Slack, 이메일, SMS 등으로 전송
✅ 8. NestJS + Prometheus로 메트릭 수집
📂 prometheus.yml
global:
scrape_interval: 15s
scrape_configs:
- job_name: 'nestjs'
metrics_path: /metrics
static_configs:
- targets: ['localhost:3000']
💡 메트릭 수집으로 CPU 사용량, 메모리 사용량, HTTP 요청 수를 실시간 모니터링
✅ 9. 자동 복구 상태 모니터링
모니터링 항목 도구
애플리케이션 상태 | Prometheus, Grafana 대시보드 |
Pod 상태 | Kubernetes Dashboard 또는 kubectl get pods |
프로세스 상태 | PM2 모니터링 (pm2 status) |
장애 알림 | Grafana Alert, Slack, PagerDuty |
✅ 결론: NestJS 자동 복구와 장애 대응 완벽 구축
✅ PM2와 Kubernetes Liveness Probe로 서비스 안정성 확보
✅ Circuit Breaker로 외부 API 호출 안정화
✅ Grafana와 Prometheus로 실시간 상태 모니터링
✅ 장애 발생 시 빠른 복구와 알림 전송으로 운영 효율 향상
다음 글에서는 NestJS 프로젝트에서 데이터 파이프라인을 구축하여 실시간 분석과 로그 수집을 통합하는 방법을 소개합니다! 📈
🔍 다음 글 예고: NestJS 실시간 데이터 파이프라인 – Kafka와 ELK 스택 통합
📌 다음 편: 30. NestJS 데이터 파이프라인 구축 가이드
NestJS 장애 복구,NestJS 자동 복구,NestJS Kubernetes 복구,NestJS Liveness Probe,NestJS Circuit Breaker,NestJS PM2,NestJS 모니터링,NestJS 장애 탐지,NestJS Grafana Alert,NestJS 복구 전략
'project > NestJS + Kubernetes & 마이크로서비스 배포' 카테고리의 다른 글
- Total
- Today
- Yesterday
- 딥러닝
- 웹개발
- Python
- SEO최적화
- AI챗봇
- REACT
- PostgreSQL
- Ktor
- fastapi
- App Router
- nextJS
- 프론트엔드
- CI/CD
- Prisma
- SEO 최적화
- 개발블로그
- kotlin
- seo 최적화 10개
- NestJS
- 프론트엔드면접
- JAX
- gatsbyjs
- 파이썬알고리즘
- 백엔드개발
- Docker
- rag
- flax
- nodejs
- Next.js
- llm
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |