HAProxy


Setp 1 - Download

Download

The Reliable, High Performance TCP/HTTP Load Balancer

Setp 2 - Install


    HA-proxy
    듀얼 CPU 환경에서 초당 2만 세션까지 연결 가능
    -> CPU 성능이 높아지면 연결 가능 세션 수 증가
    초당 1만 건 세션 연결 시 응답에 100밀리초(ms) 소요
    -> 최대 연결 개수는 하드웨어의 RAM과 file descriptor에 의해 결정됨
    -> 세션당 16KB 사용 시 3만 세션당 1G RAM 필요

    - 원문 참조
    www.haproxy.org


    The session rate
    This factor is very important, because it directly determines when the load balancer will not be able to distribute all the requests it receives. It is mostly dependant on the CPU. Sometimes, you will hear about requests/s or hits/s, and they are the same as sessions/s in HTTP/1.0 or HTTP/1.1 with keep-alive disabled. Requests/s with keep-alive enabled is generally much higher (since it significantly reduces system-side work) but is often meaningless for internet-facing deployments since clients often open a large amount of connections and do not send many requests per connection on avertage. This factor is measured with varying object sizes, the fastest results generally coming from empty objects (eg: HTTP 302, 304 or 404 response codes). Session rates around 100,000 sessions/s can be achieved on Xeon E5 systems in 2014.

    The session concurrency
    This factor is tied to the previous one. Generally, the session rate will drop when the number of concurrent sessions increases (except with the epoll or kqueue polling mechanisms). The slower the servers, the higher the number of concurrent sessions for a same session rate. If a load balancer receives 10000 sessions per second and the servers respond in 100 ms, then the load balancer will have 1000 concurrent sessions. This number is limited by the amount of memory and the amount of file-descriptors the system can handle. With 16 kB buffers, HAProxy will need about 34 kB per session, which results in around 30000 sessions per GB of RAM. In practise, socket buffers in the system also need some memory and 20000 sessions per GB of RAM is more reasonable. Layer 4 load balancers generally announce millions of simultaneous sessions because they need to deal with the TIME_WAIT sockets that the system handles for free in a proxy. Also they don't process any data so they don't need any buffer. Moreover, they are sometimes designed to be used in Direct Server Return mode, in which the load balancer only sees forward traffic, and which forces it to keep the sessions for a long time after their end to avoid cutting sessions before they are closed.

    The data forwarding rate
    This factor generally is at the opposite of the session rate. It is measured in Megabytes/s (MB/s), or sometimes in Gigabits/s (Gbps). Highest data rates are achieved with large objects to minimise the overhead caused by session setup and teardown. Large objects generally increase session concurrency, and high session concurrency with high data rate requires large amounts of memory to support large windows. High data rates burn a lot of CPU and bus cycles on software load balancers because the data has to be copied from the input interface to memory and then back to the output device. Hardware load balancers tend to directly switch packets from input port to output port for higher data rate, but cannot process them and sometimes fail to touch a header or a cookie. Haproxy on a typical Xeon E5 of 2014 can forward data up to about 40 Gbps. A fanless 1.6 GHz Atom CPU is slightly above 1 Gbps.



    - 원문 참조

    세션 속도
    이 요소는 로드 밸런서가 수신하는 모든 요청을 분산할 수 없는 시기를 직접 결정하기 때문에 매우 중요합니다. 대부분 CPU에 의존합니다. 때때로 요청 또는 적중에 대해 듣게 되며 연결 유지가 비활성화된 HTTP / 1.0 또는 HTTP /1.1 의 세션과 동일합니다. 연결 유지가 활성화된 요청은 일반적으로 훨씬 높지만(시스템 측 작업을 크게 줄이므로) 클라이언트가 종종 많은 양의 연결을 열고 평균적으로 연결당 많은 요청을 보내지 않기 때문에 인터넷 연결 배포에는 의미가 없는 경우가 많습니다. . 이 요소는 다양한 개체 크기로 측정되며 가장 빠른 결과는 일반적으로 빈 개체(예: HTTP 302, 304 또는 404 응답 코드). 2014년에는 Xeon E5 시스템에서 약 100,000 세션/초의 세션 속도를 달성할 수 있습니다.

    세션 동시성
    이 요소는 이전 요소와 연결되어 있습니다. 일반적으로 동시 세션 수가 증가하면 세션 속도가 떨어집니다( epoll 또는 kqueue 폴링 메커니즘 제외). 서버가 느릴수록 동일한 세션 속도에 대한 동시 세션 수가 더 많습니다. 로드 밸런서가 초당 10000개의 세션을 수신하고 서버가 100ms 내에 응답하면 로드 밸런서는 1000개의 동시 세션을 갖게 됩니다. 이 수는 시스템이 처리할 수 있는 메모리 양과 파일 설명자의 양에 의해 제한됩니다. 16kB 버퍼의 경우 HAProxy는 세션당 약 34kB가 필요하므로 GB당 약 30000개의 세션 이 필요합니다. 의 RAM. 실제로 시스템의 소켓 버퍼에도 약간의 메모리가 필요하며 RAM GB당 20000개 세션이 더 합리적입니다. 레이어 4 로드 밸런서 는 시스템이 프록시에서 무료로 처리하는 TIME_WAIT 소켓을 처리해야 하기 때문에 일반적으로 수백만 개의 동시 세션을 발표합니다. 또한 데이터를 처리하지 않으므로 버퍼가 필요하지 않습니다. 또한 로드 밸런서가 순방향 트래픽만 보고 닫히기 전에 세션이 끊어지는 것을 피하기 위해 종료 후 오랜 시간 동안 세션을 유지하도록 강제하는 Direct Server Return 모드 에서 사용하도록 설계되는 경우 가 있습니다.

    데이터 전달 속도
    이 요소는 일반적으로 세션 속도와 반대입니다. 메가바이트/초(MB/s) 또는 때때로 기가비트/초(Gbps)로 측정됩니다. 세션 설정 및 해제로 인한 오버헤드를 최소화하기 위해 큰 개체에서 가장 높은 데이터 속도를 달성합니다. 큰 개체는 일반적으로 세션 동시성을 증가시키며 높은 데이터 속도와 높은 세션 동시성은 큰 창을 지원하기 위해 많은 양의 메모리를 필요로 합니다. 데이터를 입력 인터페이스에서 메모리로 복사한 다음 다시 출력 장치로 복사해야 하기 때문에 높은 데이터 속도는 소프트웨어 로드 밸런서에서 많은 CPU 및 버스 주기를 소모합니다. 하드웨어 로드 밸런서는 더 높은 데이터 속도를 위해 패킷을 입력 포트에서 출력 포트로 직접 전환하는 경향이 있지만 처리할 수 없고 헤더나 쿠키를 터치하지 못하는 경우가 있습니다. 2014년의 일반적인 Xeon E5의 Haproxy는 최대 약 40Gbps . 팬이 없는 1.6GHz Atom CPU는 1Gbps보다 약간 높습니다.

    # yum install -y pcre2-devel zlib-devel openssl-devel systemd-devel
    compile
    
     
    
    cd /usr/local/src/
    wget https://www.haproxy.org/download/2.8/src/haproxy-2.8.6.tar.gz
    tar zxvf haproxy-2.8.6.tar.gz
    cd haproxy-2.8.6
    make -j $(nproc) TARGET=linux-glibc USE_OPENSSL=1 USE_SYSTEMD=1 USE_LUA=1  USE_PCRE2=1 USE_PCRE2_JIT=1 USE_ZLIB=1 
    make PREFIX=/usr/local/haproxy install
    make install
    ln -sf /usr/local/haproxy/sbin/haproxy /usr/local/bin/haproxy
    
    
    
    cat > /etc/systemd/system/haproxy.service << 'EOL'
    [Unit]
    Description=HAProxy Load Balancer
    After=network-online.target
    Wants=network-online.target
    
    [Service]
    Environment="CONFIG=/etc/haproxy/haproxy.cfg" "PIDFILE=/run/haproxy.pid"
    EnvironmentFile=/etc/sysconfig/haproxy
    ExecStartPre=/usr/local/sbin/haproxy -f $CONFIG -c -q $OPTIONS
    ExecStart=/usr/local/sbin/haproxy -Ws -f $CONFIG -p $PIDFILE $OPTIONS
    ExecReload=/usr/local/sbin/haproxy -f $CONFIG -c -q $OPTIONS
    ExecReload=/bin/kill -USR2 $MAINPID
    SuccessExitStatus=143
    KillMode=mixed
    Type=notify
    
    [Install]
    WantedBy=multi-user.target
    
    EOL
    echo 'OPTIONS="-Ws"' > /etc/sysconfig/haproxy
    
    
    X-forwarded-for
    1. haproxy 설정
    
    global
        # to have these messages end up in /var/log/haproxy.log you will
        # need to:
        #
        # 1) configure syslog to accept network log events.  This is done
        #    by adding the '-r' option to the SYSLOGD_OPTIONS in
        #    /etc/sysconfig/syslog
        #
        # 2) configure local2 events to go to the /var/log/haproxy.log
        #   file. A line like the following can be added to
        #   /etc/sysconfig/syslog
        #
        #    local2.*                       /var/log/haproxy.log
        #
        log         127.0.0.1 local2
    
        chroot      /var/lib/haproxy
        pidfile     /var/run/haproxy.pid
        maxconn     10240
        user        haproxy
        group       haproxy
        daemon
    
        # turn on stats unix socket
        stats socket /var/lib/haproxy/stats
    #    tune.ssl.default-dh-param 2048  # ssl 인증서 부분 sha2
    #---------------------------------------------------------------------
    # common defaults that all the 'listen' and 'backend' sections will
    # use if not designated in their block
    #---------------------------------------------------------------------
    defaults
        mode                    http
        log                     global
        option                  httplog
        option                  dontlognull
        option http-server-close
        option forwardfor       except 127.0.0.0/8
        option                  redispatch
        retries                 3
        timeout http-request    10s
        timeout queue           1m
        timeout connect         10s
        timeout client          1m
        timeout server          1m
        timeout http-keep-alive 10s
        timeout check           10s
        maxconn                 4096
    
    
    #---------------------------------------------------------------------
    # main frontend which proxys to the backends
    #---------------------------------------------------------------------
    
    frontend domain.web80
            bind 192.168.10.80:80
            stats uri /haproxy?stats
            mode http
            option httplog
            option forwardfor header X-Real-IP
            option http-server-close
            option accept-invalid-http-request
            default_backend             webserver
    
    
    #frontend domain.https
    #        bind *:443   ssl crt /usr/local/ssl/ssl.aaa.co.kr/ssl.aaa.co.kr.pem crt /usr/local/ssl/ssl.bbb.com/ssl.bbb.com.pem
    #        use_backend bk_cert1 if { ssl_fc_sni ssl.aaa.co.kr } # content switching based on SNI
    #        use_backend bk_cert2 if { ssl_fc_sni ssl.bbb.com } # content switching based on SNI
    #        mode            http
    #       option httplog
    #       option forwardfor header X-Real-IP
    #       option http-server-close
    #       option accept-invalid-http-request
    
    #       reqadd          X-Forwarded-Proto: https
    #       default_backend             webserver
    
    
    #---------------------------------------------------------------------
    # round robin balancing between the various backends
    #---------------------------------------------------------------------
    backend webserver
        balance     roundrobin
        default-server inter 3s fall 3 rise 2
        server  webserver1 192.168.10.81:80 check
        server  webserver2 192.168.10.82:80 check
    
    
    
    ngnix.conf
    http {
        set_real_ip_from 192.168.10.0/24;
        real_ip_header X-forwarded-For;
    	
    	
    upstream_php
    	proxy_set_header Upgrade $http_upgrade;
    	proxy_set_header Connection keep-alive;
    	proxy_set_header Host $http_host;
    	proxy_cache_bypass $http_upgrade;       
    	proxy_set_header X-Real-IP $remote_addr;
    	proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;