[Nginx] 로드밸런싱 최적화된 트래픽 분산 설정하기

궁금하면 500원·2024년 12월 22일

데브옵스

목록 보기
24/36

설정에 대해 주요 포인트별로 설명드리겠습니다

1. 로드밸런싱 방식

  • Round Robin (기본): 순차적으로 요청을 분배
  • IP Hash: 클라이언트 IP 기반으로 항상 같은 서버로 요청 분배
  • Least Connections: 연결 수가 가장 적은 서버로 요청 분배

2. 서버 설정 옵션

  • weight: 서버별 가중치 설정
  • backup: 주 서버들이 모두 다운됐을 때만 사용
  • max_fails: 헬스체크 실패 허용 횟수
  • fail_timeout: 실패 시 해당 시간동안 제외

3. 프록시 설정

  • proxy_set_header: 원본 요청 정보를 백엔드로 전달
  • proxy_connect_timeout: 연결 타임아웃
  • health_check: 주기적인 헬스체크

4. SSL/보안 설정

  • SSL 인증서 설정
  • HTTPS 리다이렉션 등
# HTTP 업스트림 서버 그룹 정의
upstream backend_service1 {
    # 라운드 로빈 방식 (기본값)
    server 10.0.0.1:8001 weight=3;  # 가중치 3
    server 10.0.0.2:8001 weight=2;  # 가중치 2
    server 10.0.0.3:8001;           # 기본 가중치 1
}

upstream backend_service2 {
    # IP 해시 방식
    ip_hash;
    server 10.0.0.4:8002;
    server 10.0.0.5:8002;
    server 10.0.0.6:8002 backup;    # 백업 서버
}

upstream backend_service3 {
    # 최소 연결 방식
    least_conn;
    server 10.0.0.7:8003 max_fails=3 fail_timeout=30s;
    server 10.0.0.8:8003 max_fails=3 fail_timeout=30s;
}

# HTTPS 서버 설정
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate /etc/nginx/ssl/certificate.crt;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    # 서비스1 로드밸런싱
    location /service1/ {
        proxy_pass http://backend_service1;
        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 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;

        # 헬스체크 설정
        health_check interval=5s fails=3 passes=2;
    }

    # 서비스2 로드밸런싱
    location /service2/ {
        proxy_pass http://backend_service2;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        # 기본적인 프록시 설정 포함
    }

    # 서비스3 로드밸런싱
    location /service3/ {
        proxy_pass http://backend_service3;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        # 기본적인 프록시 설정 포함
    }

    # 에러 페이지 설정
    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
        root /usr/share/nginx/html;
    }
}

추가로 고려할 수 있는 설정들

1. 세션 유지

upstream backend {
    ip_hash;  # 또는
    sticky cookie srv_id expires=1h domain=.example.com path=/;
}

2. 캐시 설정

proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
location / {
    proxy_cache my_cache;
    proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
}
profile
에러가 나도 괜찮아 — 그건 내가 배우고 있다는 증거야.

0개의 댓글