stack-analysis
CHAPTER 112 / 120
읽기 약 2분
FUNCTION
로드 밸런싱: Nginx + 헬스 체크
핵심 개념
Nginx upstream·health check·sticky session·blue-green — 무중단 확장.
본문
Nginx Load Balancer
upstream api_backend {
least_conn; # 또는 round_robin, ip_hash, hash $cookie_session
server api1.internal:3000 max_fails=3 fail_timeout=30s;
server api2.internal:3000 max_fails=3 fail_timeout=30s;
server api3.internal:3000 max_fails=3 fail_timeout=30s backup; # 백업
# 헬스 체크 (nginx plus만)
# health_check uri=/health interval=10s;
keepalive 64;
}
server {
listen 443 ssl http2;
server_name api.example.com;
location / {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 타임아웃
proxy_connect_timeout 5s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# WebSocket 지원
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
}헬스 체크 (Application Level)
// /health endpoint
app.get('/health', async (req, res) => {
try {
// 핵심 의존성 검증
await db.$queryRaw`SELECT 1`;
await redis.ping();
res.json({
status: 'healthy',
version: process.env.GIT_SHA,
uptime: process.uptime(),
});
} catch (err) {
res.status(503).json({ status: 'unhealthy', error: err.message });
}
});
// /ready (LB 진입 가능 여부)
let ready = false;
app.listen(PORT, async () => {
// 워밍업
await db.$connect();
await redis.connect();
ready = true;
});
app.get('/ready', (req, res) => {
res.status(ready ? 200 : 503).end();
});Sticky Session (필요 시)
# IP 기반 (간단)
upstream backend {
ip_hash;
server api1:3000;
server api2:3000;
}
# Cookie 기반 (정확)
upstream backend {
hash $cookie_sessionid consistent;
server api1:3000;
server api2:3000;
}
# 또는 Redis 세션 사용 시 sticky 불필요
# → 어느 서버든 세션 접근 가능클라우드 LB 비교
AWS ALB (Application Load Balancer)
- L7 (HTTP/HTTPS)
- WebSocket·gRPC 지원
- $0.0225/hr + $0.008/LCU-hr
AWS NLB (Network Load Balancer)
- L4 (TCP)
- 매우 빠름
- $0.0225/hr + $0.006/NLCU-hr
GCP Cloud Load Balancer
- 글로벌 anycast
- HTTP/HTTPS, TCP/UDP
- $18/mo + $0.008/GB
Cloudflare Load Balancing
- 무료 plan: 1 LB, 5 origin
- Pro: $5/origin/mo
- 글로벌 + 헬스 체크 + 지역 라우팅Blue-Green 배포
[현재] Blue 환경 → 100% 트래픽
[배포]
1. Green 환경에 새 버전 배포
2. Green 헬스 체크 통과
3. LB 설정 → Green으로 전환
4. Blue 유지 (즉시 롤백 가능)
[검증 후]
- 1일 후 Blue 종료
- 또는 다음 배포의 Blue로 활용# Vercel — 자동 Blue-Green
# Production deployment + Preview deployments
# main 브랜치 push → 새 deployment 빌드
# 빌드 성공 → 도메인 알리아스 전환 (즉시)
# 실패 → 이전 버전 유지Canary 배포 (점진)
[Stage 1] 5% 트래픽 → 새 버전
- 1시간 모니터
- 에러율 정상
[Stage 2] 25% → 새 버전
- 2시간 모니터
[Stage 3] 100% → 새 버전
- 자동 또는 수동 승격
# Cloudflare Load Balancer Weights
- backend-v1: weight 95
- backend-v2: weight 5자동 스케일링
# Kubernetes HPA
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: api
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: api
minReplicas: 3
maxReplicas: 30
metrics:
- type: Resource
resource:
name: cpu
target: { type: Utilization, averageUtilization: 70 }
- type: Resource
resource:
name: memory
target: { type: Utilization, averageUtilization: 80 }
# AWS Auto Scaling Group
- min: 3, desired: 5, max: 30
- CPU > 70% 5분 → +2 인스턴스
- CPU < 30% 10분 → -1 인스턴스Connection Draining (안전 종료)
// SIGTERM 받으면 graceful shutdown
process.on('SIGTERM', async () => {
console.log('SIGTERM received, draining connections');
// 1. /ready 503 응답 → LB가 트래픽 중단
ready = false;
// 2. 진행 중 요청 완료 대기 (30초)
await new Promise(r => setTimeout(r, 5000));
// 3. 새 요청 거부
server.close(() => {
console.log('Server closed');
});
// 4. 의존성 종료
await db.$disconnect();
await redis.quit();
process.exit(0);
});다음 챕터
CH.113 "마이크로서비스: 분해 기준과 통신".
AI 프롬프트
🤖 AI에게 잘 물어보는 법 — 모델·전략별 프롬프트
Claude
무료: Sonnet 4.6 / Pro $20/mo: Opus 4.6
내 코드의 로드 밸런싱 부분을 분석해서 실전 분석 + 개선 우선순위를 알려줘.
ChatGPT
무료: GPT-5.5 / Plus $20/mo: GPT-5.5 Pro
로드 밸런싱 관련 베스트 프랙티스 5가지를 비교 분석해서 패턴 추출를 알려줘.
Gemini
무료: 2.5 Flash / Pro $19.99/mo: 3.1 Pro
내 프로젝트 전체에서 로드 밸런싱 최적화 가능 위치를 보고해줘.
Grok
무료: Grok 4.1 / SuperGrok $30/mo
2026년 한국 시장의 로드 밸런싱 트렌드를 솔직히 알려줘.
⭐ 이것만 기억하세요
로드 밸런싱: Nginx + 헬스 체크는 이 3가지만 확실히 잡으세요
1.Nginx + upstream + health check = 무료 LB
2.Blue-Green = 무중단 + 즉시 롤백, Canary = 점진 검증
3.SIGTERM graceful shutdown으로 안전 종료
공유하기
진행도 112 / 120