• HAproxy(High Availability proxy)는 고가용성 프록시를 의미 → HAProxy는 소프트웨어 기반 L7 스위치
  • HAproxy는 C 언어로 작성
  • 무료 오픈소스 프로그램
  • HAproxy는 TCP/HTTP 로드 밸런서로 프록시 솔루션에 사용
  • HAproxy의 일반적인 용도는 웹서버, DB 서버 등 부하를 분산시키는 용도로 많이 사용
  • HAProxy는 기존의 하드웨어 스위치를 대체하는 소프트웨어 로드 밸런서 → 네트워크 스위치에서 제공하는 L4, L7 기능 및 로드 밸런서 기능을 제공
  • 설치가 쉽고 빠르기에 서비스 이중화(HA- High Availability)를 구성하는데 주로 사용

1. HAproxy 로드밸런서 테스트 준비사항 → VM 환경에서 진행

  • HAproxy를 설치할 VM 1대, 웹서버 VM 2대, 테스트 서버 1대
    1. HAproxy 서버 → 192.168.100.101, centos7, hostname : haproxy, 60000 → 80포트로 proxy
    2. 첫번째 web 서버 → 192.168.100.201, centos7, hostname: web1
    3. 두번째 web 서버 → 192.168.100.202, centos7, hostname: web2
    4. 테스트 서버 → 192.168.100.10, centos7, hostname: test

2. HAproxy.conf 옵션

  • haproxy.cfg 의 옵션은 (https://cbonte.github.io/haproxy-dconv/) 에서 자세하게 확인 가능
  • 기본적인 옵션만 아래 설명 → 여러 섹션으로 나누어져 있으며 섹션 하단에 파라미터를 추가하는 방식으로 구성

2.1. global 구간

  • -daemon
    • 백그라운드에서 HAproxy 서비스 실행
    • 데몬형식 fork 하면서 실행 하는 파라미터
    • 만약 daemon을 추가 하지 않을 경우 포그라운드에서 실행 → 실행할 때 &를 추가하여 명시적으로 백그라운드에서 실행되게 해야함
  • -maxconn
    • 최대 연결 수를 지정
    • (ulimit -n) 을 통해 해당 서버의 기본 프로세스가 오픈 할 수 있는 갯수 만큼 지정 가능

2.2. defaults 구간

  • -mode (http,tcp,health)
    • tcp→ 해당 포트에 대한 어플리케이션 프록시
    • http→ http 인스턴스에서 작동
    • health→ 단순한 health check 모드
  • -timeout connect
    • 전체 외부 클라이언트에서 실제 real 서버 까지의 time out 설정
  • -timeout client
    • 외부 클라이언트에서 vip(virtual IP)까지의 timeout 설정
  • -timeout server
    • vip(virtual IP) 서버에서 실제 real 서버 까지의 timeout 설정

2.3. frontend 구간

  • -bind
    • bind 는 apache 의 binding 설정과 비슷 하며, 해당 서버로 listening 되는 아이피와 포트를 지정
  • -default_backend
    • frontend 에서 받은 정보를 backend server로 보낼 이름을 지정
    • servers 라는 backend 설정된 아이피로 포워딩

2.4. backend servers 구간 → server <name> <address>[:[port]][param*]

  • 위 형태로 명시된 아이피와 포트로 데이터를 전송

2.5. listen 구간

  • frontend + backend 한번에 설정 가능한 섹션


3. HAproxy balance 옵션

  • backend 에서 사용 할 balancing 알고리즘을 설정 가능

3.1. roundrobin

  • 순서대로 데이터를 전송

3.2. static-rr

  • 서버에 weight 가중치를 부여해, 부여된 가중치에 따라 데이터 전송

3.3. balance_url_param

  • HTTP GET 요청에 대해서 특정 패턴이 있는지 여부 조사후 조건에 맞는 서버로 트래픽 전송
  • 조건이 없는 경우 roundrobin 으로 트래픽 전송

3.4. balance hdr

  • HTTP Header 에서 hdr(name) 으로 지정된 조건이 있는 경우에 대해서만 트래픽 전송
  • 조건이 없는경우 roundrobin 으로 트래픽 전송


4. HAproxy 패키지 설치

4.1. 첫번째 방법. yum으로 haproxy 패키지 설치

  • HAproxy는 버전에 따라 설정이 약간씩 다르기에 필요한 버전을 수동으로 다운받는게 좋음
    $ yum -y install haproxy

4.2. 두번째 방법. HAproxy 패키지 수동으로 설치 → HAproxy 2.3.9 버전 설치

  • 아래 명령어를 입력하여 haproxy 2.3.9 버전 설치 파일을 다운로드

    $ cd /usr/local/lib
    
    # haproxy 2.3.9 버전 파일 설치
    $ curl -O http://www.haproxy.org/download/2.3/src/haproxy-2.3.9.tar.gz
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100 2860k  100 2860k    0     0   564k      0  0:00:05  0:00:05 --:--:--  672k
    
    # 다운받은 haproxy 2.3.9 버전 설치 파일 확인
    $ ls /usr/local/lib
    haproxy-2.3.9.tar.gz
  • 설치파일을 압축해제
    $ tar zxf haproxy-2.3.9.tar.gz
    $ ls -al /usr/local/lib
    total 2868
    drwxr-xr-x.  3 root root      55 Aug  1 13:09 .
    drwxr-xr-x. 12 root root     131 Apr 30  2020 ..
    drwxrwxr-x  11 root root    4096 Mar 30 16:38 haproxy-2.3.9
    -rw-r--r--   1 root root 2928660 Aug  1 13:08 haproxy-2.3.9.tar.gz
  • HAproxy를 설치하기 전에 의존성 패키지를 설치
    $ yum install gcc openssl openssl-devel pcre-static pcre-devel systemd-devel -y
  • HAproxy 2.3.9 설치 옵션을 설정
    1. TARGET=linux-glibc → HAProxy 2.0 부터는 "linux2628" 대신에 "linux-glibc" 로 "TARGET"이 변경
    2. USE_OPENSSL=1 → SSL 인증서를 활성화 하기 위해서 USE_OPENSSL를 활성화
    3. USE_PCRE=1 → 펄(PERL) 호환 정규 표현식을 사용하기 위해 활성화
    4. USE_ZLIB=1 → http 압축을 이용하기 위해 활성화
    5. USE_SYSTEMD=1 → systemd 를 통해서 서비스를 컨트롤 하기 위해서 USE_SYSTEMD도 활성화
      $ cd /usr/local/lib/haproxy-2.3.9
      $ make TARGET=linux-glibc USE_OPENSSL=1 USE_PCRE=1 USE_ZLIB=1 USE_SYSTEMD=1
       CC      src/ev_poll.o
       CC      src/ev_epoll.o
       CC      src/ssl_sample.o
       CC      src/ssl_sock.o
      [...생략]
  • HAproxy를 설치
    $ make install
    ‘haproxy’ -> ‘/usr/local/sbin/haproxy’
    ‘doc/haproxy.1’ -> ‘/usr/local/share/man/man1/haproxy.1’
    install: creating directory ‘/usr/local/doc’
    install: creating directory ‘/usr/local/doc/haproxy’
    ‘doc/configuration.txt’ -> ‘/usr/local/doc/haproxy/configuration.txt’
    ‘doc/management.txt’ -> ‘/usr/local/doc/haproxy/management.txt’
    ‘doc/seamless_reload.txt’ -> ‘/usr/local/doc/haproxy/seamless_reload.txt’
    ‘doc/architecture.txt’ -> ‘/usr/local/doc/haproxy/architecture.txt’
    ‘doc/peers-v2.0.txt’ -> ‘/usr/local/doc/haproxy/peers-v2.0.txt’
    ‘doc/regression-testing.txt’ -> ‘/usr/local/doc/haproxy/regression-testing.txt’
    ‘doc/cookie-options.txt’ -> ‘/usr/local/doc/haproxy/cookie-options.txt’
    ‘doc/lua.txt’ -> ‘/usr/local/doc/haproxy/lua.txt’
    ‘doc/WURFL-device-detection.txt’ -> ‘/usr/local/doc/haproxy/WURFL-device-detection.txt’
    ‘doc/proxy-protocol.txt’ -> ‘/usr/local/doc/haproxy/proxy-protocol.txt’
    ‘doc/linux-syn-cookies.txt’ -> ‘/usr/local/doc/haproxy/linux-syn-cookies.txt’
    ‘doc/SOCKS4.protocol.txt’ -> ‘/usr/local/doc/haproxy/SOCKS4.protocol.txt’
    ‘doc/network-namespaces.txt’ -> ‘/usr/local/doc/haproxy/network-namespaces.txt’
    ‘doc/DeviceAtlas-device-detection.txt’ -> ‘/usr/local/doc/haproxy/DeviceAtlas-device-detection.txt’
    ‘doc/51Degrees-device-detection.txt’ -> ‘/usr/local/doc/haproxy/51Degrees-device-detection.txt’
    ‘doc/netscaler-client-ip-insertion-protocol.txt’ -> ‘/usr/local/doc/haproxy/netscaler-client-ip-insertion-protocol.txt’
    ‘doc/peers.txt’ -> ‘/usr/local/doc/haproxy/peers.txt’
    ‘doc/close-options.txt’ -> ‘/usr/local/doc/haproxy/close-options.txt’
    ‘doc/SPOE.txt’ -> ‘/usr/local/doc/haproxy/SPOE.txt’
    ‘doc/intro.txt’ -> ‘/usr/local/doc/haproxy/intro.txt’
  • 설치된 HAproxy 버전을 확인 → HAproxy 2.3.9로 잘 설치된 것을 확인
    $ /usr/local/sbin/haproxy -v
    HA-Proxy version 2.3.9-53945bf 2021/03/30 - https://haproxy.org/
    Status: stable branch - will stop receiving fixes around Q1 2022.
    Known bugs: http://www.haproxy.org/bugs/bugs-2.3.9.html
    Running on: Linux 3.10.0-1160.36.2.el7.x86_64 #1 SMP Wed Jul 21 11:57:15 UTC 2021 x86_64
  • HAProxy 서비스 예제 파일을 다운로드
    $ curl "http://git.haproxy.org/?p=haproxy-2.3.git;a=blob_plain;f=contrib/systemd/haproxy.service.in" -o /etc/systemd/system/haproxy.service
    % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                   Dload  Upload   Total   Spent    Left  Speed
    100  1405    0  1405    0     0    550      0 --:--:--  0:00:02 --:--:--   550
  • HAproxy 서비스 예제 파일 수정

    1. $CONFIG 값 설정 → /etc/haproxy/haproxy.cfg

    2. $EXTRAOPTS 값 설정 → /run/haproxy-master.sock

    3. $PIDFILE 값 설정 → /run/haproxy.pid

      $ vi /etc/systemd/system/haproxy.service
      [Unit]
      Description=HAProxy Load Balancer
      After=network-online.target
      Wants=network-online.target
      
      [Service]
      EnvironmentFile=-/etc/default/haproxy
      EnvironmentFile=-/etc/sysconfig/haproxy
      Environment="CONFIG=/etc/haproxy/haproxy.cfg" "PIDFILE=/run/haproxy.pid" "EXTRAOPTS=-S /run/haproxy-master.sock"
      
      # 수정 전 내용 아래
      ExecStartPre=@SBINDIR@/haproxy -f $CONFIG -c -q $EXTRAOPTS
      ExecStart=@SBINDIR@/haproxy -Ws -f $CONFIG -p $PIDFILE $EXTRAOPTS
      ExecReload=@SBINDIR@/haproxy -Ws -f $CONFIG -c -q $EXTRAOPTS
      
      # 수정 후 내용 아래
      ExecStartPre=/usr/local/sbin/haproxy -f /etc/haproxy/haproxy.cfg -c -q -S /run/haproxy-master.sock
      ExecStart=/usr/local/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -S /run/haproxy-master.sock
      ExecReload=/usr/local/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -c -q -S /run/haproxy-master.sock
      
      ExecReload=/bin/kill -USR2 $MAINPID
      KillMode=mixed
      Restart=always
      SuccessExitStatus=143
      Type=notify
      
      # The following lines leverage SystemD's sandboxing options to provide
      # defense in depth protection at the expense of restricting some flexibility
      # in your setup (e.g. placement of your configuration files) or possibly
      # reduced performance. See systemd.service(5) and systemd.exec(5) for further
      # information.
      
      # NoNewPrivileges=true
      # ProtectHome=true
      # If you want to use 'ProtectSystem=strict' you should whitelist the PIDFILE,
      # any state files and any other files written using 'ReadWritePaths' or
      # 'RuntimeDirectory'.
      # ProtectSystem=true
      # ProtectKernelTunables=true
      # ProtectKernelModules=true
      # ProtectControlGroups=true
      # If your SystemD version supports them, you can add: @reboot, @swap, @sync
      # SystemCallFilter=~@cpu-emulation @keyring @module @obsolete @raw-io
      
      [Install]
      WantedBy=multi-user.target
  • HAproxy가 사용할 디렉토리를 생성
    $ mkdir -p /etc/haproxy
    $ mkdir -p /var/log/haproxy
    $ mkdir -p /var/lib/haproxy
    $ mkdir -p /etc/haproxy/certs
    $ mkdir -p /etc/haproxy/errors/


5. haproxy.conf 파일 생성 또는 수정

5.1. haproxy.conf 파일에 들어가는 내용 옵션 확인

$ vi /etc/haproxy/haproxy.cfg
#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
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         # syslog. UDP 514번 포트 Open 필요

    chroot      /var/lib/haproxy         # 모든 동작은 /var/lib/haproxy에서 수행, 보안 상승
    pidfile     /var/run/haproxy.pid     # 실행 pid명
    maxconn     4000                     # 프로세스 당 최대 연결 수치
    user        haproxy                  # haproxy 서비스 사용자
    group       haproxy                  # harpoxy 서비스 그룹
    daemon                               # background로 실행될 수 있도록 설정

    # turn on stats unix socket
    stats socket /var/lib/haproxy/stats



#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults                                 # front, back, listen에 관련 설정 부분
    mode                    http         # http 프로토콜을 사용하는 로드벨런싱 모드
    log                     global       # 로그는 global에 설정한 방법으로 사용
    option                  httplog      # 기본 Log는 SIP, DIP와 Name만 표기됨, 해당 옵션을 사용하면 디테일하게 Log 표시
    option                  dontlognull  # Log 비대화 방지 -> Probe(정찰, 스캔과 같은 불필요한 기록을 HAProxy Log 기록 X
    option http-server-close             # 클라이언트와 리얼 서버 연결 종료시, 디폴트로 유휴 대기하지 않고, 서버에서 Handshake를 종료
                                         # 더 빠른 새로운 세션을 준비할 수 있도록 해줌
                                         # 디폴트 옵션에 선언되어 있어도, 인스턴스 별로 no 옵션으로 제외처리 가능
    option forwardfor       except 127.0.0.0/8     # 서버에 대한 응답을 HAProxy가 받기 때문에(VIP), 리얼 서버 IP를 HTTP 헤더에 표기하는 옵션
    option                  redispatch   # mode HTTP에서 Cookie에 지정된 Real 서버가 다운되면, 외부 클라이언트가 쿠키를 플로시하기 전에 서비스에 문제 발생 가능
                                         # redispatch 옵션을 통해 프로시 지속성을 무시하고 쿠키, 세션 재분재를 실행 -> retries값이 0보다 커야함
    retries                 3            # redispatch 횟수 결정
    timeout http-request    10s          # Request시의 헤더에만 적용. Dos 방어를 위해, HTTP 요청 타임 아웃시간 설정 -> 클라이언트의 연결 타임아웃과는 관계 X, HAProxy의 옵션
    timeout queue           1m           # 서버의 maxconn에 도달시, 무한정 보류 상태로 두지 않고 HTTP 503 응답을 보내면서 연결을 버리기까지의 시간
    timeout connect         10s          # TCP 패킷 손실을 막기 위한 Real 서버로의 연결 최대 지연시간 설정 -> Backend에 적용, 전역에도 적용 가능
    timeout client          1m           # 외부 클라이언트의 요청이나 데이터와의 연결 최대 시 ->  http-request가 선행, 서버 안정성에 기여
    timeout server          1m           # 서버가 데이터를 승인하거나, 전송해야 할 때의 연결 최대 시간
    timeout http-keep-alive 10s          # 클라이언트의 요청에 따른 응답 전송 후, 다음 요청까지의 대기 시간 -> http-request가 선행 필수
    timeout check           10s          # timeout server와 동일하거나 작은 값을 가져야함
    maxconn                 3000         # 프로세스당 최대 연결 개수

#---------------------------------------------------------------------
# main frontend which proxys to the backends
#---------------------------------------------------------------------
frontend http
    bind: *:80                               # haproxy 구동시 사용할 포트를 지정 -> 클라이언트의 연결을 받는 부분(WAF 기능과 유사)
    acl url_static       path_beg       -i /static /images /javascript /stylesheets
    acl url_static       path_end       -i .jpg .gif .png .css .js

    use_backend static          if url_static    # ACL에서 정의한 style들을 backend static으로 전송
    default_backend             static           # 아래 backend 중에서 static 부분을 사용 -> 미리 여러개 설정해놓고 선택


#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such
#---------------------------------------------------------------------
backend static                                   # 실제 접속시 로드밸런싱하는 서버
    balance     roundrobin                       # roundrobin은 무조건 한번씩 번갈아 접속시키는 방식 -> source 값을 이용
    server      static 192.168.100.201:80 check  # 포워딩할 서버 IP와 포트 설정
    server      static 192.168.100.202:80 check  # 포워딩할 서버 IP와 포트 설정

#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend app
    balance     roundrobin
    server  app1 127.0.0.1:5001 check
    server  app2 127.0.0.1:5002 check
    server  app3 127.0.0.1:5003 check
    server  app4 127.0.0.1:5004 check


#listen                                          # 프론트/백엔드 연결의 포트/옵션등 정의 -> TCP 제어나 Proxy에 주로 사용
#listen stats                                    # "stats"라는 이름으로 listen 지정
#    bind *:9000                                 # 접속 포트 지정
#    stats enable
#    stats realm Haproxy Statistics              # 브라우저 타이틀
#    stats uri /haproxy_stats                    # stat 를 제공할 URI
#    #stats auth Username:Password               # 인증이 필요하면 추가

5.2. haproxy.conf 파일에 넣은 내용 → 간단하게 적용

global
  log  127.0.0.1 local2

  chroot  /var/lib/haproxy
  pidfile /var/run/haproxy.pid
  maxconn 4000
  daemon

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  3000

frontend http
    bind *:80
    acl url_static       path_beg       -i /static /images /javascript /stylesheets
    acl url_static       path_end       -i .jpg .gif .png .css .js

    default_backend  back_server


backend back_server
    balance  roundrobin
    server  web1 192.168.100.201:80 check
    server  web2 192.168.100.202:80 check



6. HAproxy의 conf 파일에 문제 없는지 Check

  • haproxy.cfg 설정이 이상 없는지 확인
    $ haproxy -f /etc/haproxy/haproxy.cfg -c
    Configuration file is valid


7. 방화벽 해제(firewalld)

$ systemctl stop firewalld
$ systemctl disable firewalld



8. HAproxy 서버스를 원할하게 실행하기 실행을 위한 커널 파라미터 변경

8.1. net.ipv4.ip_forward = 1

  • Kernel이 패킷을 전달하게 하는 경우 사용
  • Keepalived가 네트워크 패킷을 실제 서버에 정상적으로 전달하려면 각 라우터 노드가 커널에서 IP Forward를 설정 필요

8.2. net.ipv4.ip_nonlocal_bind = 1

  • HAProxy 및 Keepalived의 로드밸런싱은 동시에 로컬이 아닌 IP 주소에 바인딩할 수 있어야함
  • 네트워크 인터페이스에 없는 주소로 바인딩할 수 있도록 해주는 커널
  • 네트워크 인터페이스가 지정된 정적 IP가 아닌 동적 IP를 바인딩할 수 있음
  • 해당 옵션이 비활성화 되어 있어도 서비스가 시작하면서 인터페이스에 특정 IP를 바인딩할 수 있으나 FailOver시 문제 발생

8.3. 커널 파라미터 적용

$ cat << EOF >> /etc/sysctl.conf
net.ipv4.ip_forward = 1
net.ipv4.ip_nonlocal_bind = 1
EOF

# /etc/sysctl.conf 파일 확인
$ cat /etc/sysctl.conf
net.ipv4.ip_forward = 1
net.ipv4.ip_nonlocal_bind = 1

# /etc/sysctl.conf 파일 내용 적용
$ sysctl --system
* Applying /usr/lib/sysctl.d/00-system.conf ...
* Applying /usr/lib/sysctl.d/10-default-yama-scope.conf ...
kernel.yama.ptrace_scope = 0
* Applying /usr/lib/sysctl.d/50-default.conf ...
kernel.sysrq = 16
kernel.core_uses_pid = 1
kernel.kptr_restrict = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.promote_secondaries = 1
net.ipv4.conf.all.promote_secondaries = 1
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
* Applying /etc/sysctl.d/99-sysctl.conf ...
net.ipv4.ip_forward = 1
net.ipv4.ip_nonlocal_bind = 1
* Applying /etc/sysctl.conf ...
net.ipv4.ip_forward = 1
net.ipv4.ip_nonlocal_bind = 1



9. 로그 설정

9.1. rsyslog 에 HAproxy 용 로그를 남기도록 설정 → /etc/rsyslog.d/haproxy.conf 파일 구성

$ vi /etc/rsyslog.d/haproxy.conf
# Provides UDP syslog reception
$ModLoad imudp
$UDPServerRun 514
$template Haproxy, "%msg%\n"

#rsyslog 에는 rsyslog 가 메세지를 수신한 시각 및 데몬 이름같은 추가적인 정보가 prepend 되므로, message 만 출력하는 템플릿 지정
# 이를 haproxy-info.log 에만 적용한다.
# 모든 haproxy 를 남기려면 다음을 주석해재, 단 access log 가 기록되므로, 양이 많다.
#local0.*   /var/log/haproxy/haproxy.log

# local0.=info 는 haproxy 에서 에러로 처리된 이벤트들만 기록하게 됨 (포맷 적용)
local0.=info    /var/log/haproxy/haproxy-info.log;Haproxy

# local0.notice 는 haproxy 가 재시작되는 경우와 같은 시스템 메세지를 기록하게됨 (포맷 미적용)
local0.notice   /var/log/haproxy/haproxy-allbutinfo.log

9.2. logroate에 HAproxy 설정을 추가 → /etc/logrotate.d/haproxy 파일 구성

  • haproxy는 재시작할 필요가 없으므로 rsyslog 를 재시작해줌

    $ vi /etc/logrotate.d/haproxy
    /var/log/haproxy/*log {
        daily
        rotate 90
        create 0644 nobody nobody
        missingok
        notifempty
        compress
        sharedscripts
        postrotate
            /bin/systemctl restart rsyslog.service > /dev/null 2>/dev/null || true
        endscript
    }
    
    # rsyslog 서비스 재시작
    $ systemctl restart rsyslog



10. HAproxy 서비스 시작

  • HAproxy 서비스 시작 및 영구 설정

    $ systemctl start haproxy
    $ systemctl enable haproxy
    
    $ systemctl status haproxy
    ● haproxy.service - HAProxy Load Balancer
       Loaded: loaded (/usr/lib/systemd/system/haproxy.service; enabled; vendor preset: disabled)
       Active: active (running) since Sun 2021-08-01 15:32:34 KST; 5s ago
     Main PID: 1030 (haproxy-systemd)
       CGroup: /system.slice/haproxy.service
               ├─1030 /usr/sbin/haproxy-systemd-wrapper -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid
               ├─1031 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -Ds
               └─1032 /usr/sbin/haproxy -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -Ds



11. Web 서버 2대(192.168.100.201, 192.168.100.202)에 nginx 설치 및 index.html 파일 변경

11.1. web1(192.168.100.201) 서버에 nginx 설치 및 index.html 파일 변경

# nginx 패키지 설치
$ yum install -y nginx

# nginx의 index.html 파일 내용 변경
$ vi /usr/share/nginx/html/index.html
hello~~~~
webser : web1
Bye

# nginx 시작
$ systemctl enable --now nginx

11.2. web1(192.168.100.202) 서버에 nginx 설치 및 index.html 파일 변경

# nginx 패키지 설치
$ yum install -y nginx

# nginx의 index.html 파일 내용 변경
$ vi /usr/share/nginx/html/index.html
hello~~~~
webser : web2
Bye

# nginx 시작
$ systemctl enable --now nginx



12. HAproxy 트래픽 테스트

  • harpoxy의 IP(192.168.100.101)으로 트래픽을 전달하면 backend에 있는 서버(192.168.100.201, 192.168.100.202)로 트래픽 전송

  • Round-Robin으로 설정하였기에 192.168.100.201과 192.168.100.202에 번갈아가면서 트래픽 전달

  • haproxy 트래픽 테스트는 해당 서버와 상관없는 192.168.100.10에서 진행

    $ while true; do curl 192.168.100.101; echo -e "\n"; sleep 3; done
    hello~~~~
    webser : web1
    Bye
    
    hello~~~~
    webser : web2
    Bye
    
    hello~~~~
    webser : web1
    Bye
    
    hello~~~~
    webser : web2
    Bye



13. HAProxy 어드민 페이지 설정

13.1. HAProxy의 상태 및 통계 제공 웹을 위한 설정

  • mode http → 통계 사이트는 http를 통해 접속
  • bind * :8020 → haproxy의 IP 에 8020 포트 접속
  • stats enable→ HAProy의 어드민 페이지를 stats로 칭하여 enable 표시함으로 사용함
  • stats auth root:hello→ HAProy의 어드민 페이지의 ID는 root, PW는 hello
  • stats uri /monitor → path를 /monitor로 지정
    # /etc/haproxy/haproxy.cfg 파일 가장 아래에 추가
    $ vi /etc/haproxy/haproxy.cfg
    listen monitor
      mode http
      bind *:8020
      stats enable
      stats auth root:hello
      stats uri /monitor

13.2. HAProxy.cfg 파일 검증 및 재시작

# 위 내용이 적합한지 검증
$ haproxy -f /etc/haproxy/haproxy.cfg -c
Configuration file is valid

$ systemctl restart haproxy

13.3. HAProxy monitor에 접속 → http://haproxy_IP:8020/monitor 접속

  • 로그인 후 monitor 화면 출력

14. 추가 HAproxy Kernel Parameter

14.1. 가장 중요한 Paramater

net.ipv4.ip_local_port_range = "1025 65534"
net.ipv4.tcp_max_syn_backlog = 100000
net.core.netdev_max_backlog = 100000
net.core.somaxconn = 65534
ipv4.tcp_rmem = "4096 16060 64060"
ipv4.tcp_wmem = "4096 16384 262144"

14.2. 작업량에 따라 조절

tcp_slow_start_after_idle = 0

14.3. iptables tuning

net.netfilter.nf_conntrack_max = 131072

14.4. HAproxy Kernel Parameter 사용시 주의 사항

  • conntrack이 잘못 구성되면 HAProxy가 최대 성능을 발휘 X
  • iptables가 활성화 되어 있으면 connection tracking 작업을 위해 iptables에 규칙이 없더라도 20%의 CPU를 소모

참고 URL : https://lascrea.tistory.com/213
참고 URL : https://findstar.pe.kr/2018/07/27/install-haproxy/
참고 URL : https://medium.com/@tamm_/%EA%B0%9C%EB%B0%9C-haproxy-%EC%84%A4%EC%B9%98-%EB%B0%8F-%EA%B8%B0%EB%B3%B8-%EC%84%A4%EC%A0%95-f4623815622
참고 URL : https://blog.develope.kr/2020/01/haproxy%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EB%A1%9C%EB%93%9C-%EB%B0%B8%EB%9F%B0%EC%8B%B1-%EA%B5%AC%EC%B6%95%ED%95%98%EA%B8%B0-2-haproxy-%EC%84%A4%EC%B9%98-%EC%84%B8%ED%8C%85%ED%95%98%EA%B8%B0/


+ Recent posts