본문 바로가기
Back-end/Deploy

Nginx를 로드밸런서로 사용하기

by whatamigonnabe 2023. 5. 7.

아래 공식 문서를 참고 했습니다.

 

Using nginx as HTTP load balancer

Using nginx as HTTP load balancer Introduction Load balancing across multiple application instances is a commonly used technique for optimizing resource utilization, maximizing throughput, reducing latency, and ensuring fault-tolerant configurations. It is

nginx.org

 

Configuration 작성하기

http {
    upstream myapp1 {
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }
    }
}

 

upstream 아래에 분산 서버의 주소를 적고, server 아래 Nginx 서버의 주소를 작성하면 됩니다.

그리고, 로드밸런싱은 여러 서버로 트래픽을 분산하는 여러 알고리즘이 존재합니다. 상황에 맞는 알고리즘을 upstream 아래와 같이 작성하면 간단하게 적용할 수 있습니다.

 

    upstream myapp1 {
        least_conn;
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

Nginx의 트래픽 분배 방식

  • round-robin — requests to the application servers are distributed in a round-robin fashion,
  • least-connected — next request is assigned to the server with the least number of active connections,
  • ip-hash — a hash-function is used to determine what server should be selected for the next request (based on the client’s IP address).

위의 세 개를 지원하며, 기본적으로 round-robin을 사용합니다. weighted round-robin을 사용하려면 아래와 같이 weight를 주면 됩니다.

upstream myapp1 {
    server srv1.example.com weight=3;
    server srv2.example.com;
    server srv3.example.com;
}

Health Check 설정

Nginx는 특정 시도를 해보고 실패를 하면, 해당 서버는 정상작동하지 않는다고 판단한 후 다음부터 트래픽을 분산시키지 않습니다. 여러 설정을 통해 각 서버마다 헬스 체크 기준을 설정할 수 있습니다.

 

키워드  설명
max_fails=n n으로 지정한 횟수만큼 실패가 일어나면 서버가 죽은 것으로 간주한다.
fail_timeout=n max_fails가 지정된 상태에서 이 값이 설정만큼 서버가 응답하지 않으면 죽은 것으로 간주한다.
down 해당 서버를 사용하지 않게 지정한다. `ip_hash;` 지시어가 설정된 상태에서만 유효하다.
backup 모든 서버가 동작하지 않을 때 backup으로 표시된 서버가 사용되고 그 전까지는 사용되지 않는다.

 

'Back-end > Deploy' 카테고리의 다른 글

로드밸런싱 이해하기  (0) 2023.05.07