HAProxy

去年因為需要建置 OpenShift 容器平台而接觸到了 HAProxy,才知道為什麼 AWS 上會有分 Application Load balancer 等不同類型的負載平衡器。

簡單的說,HAProxy 的負載平衡模式分為兩種,一種是 HTTP mode,一種是 TCP mode;也就是 Layer 7 跟 Layer 4。建置 OpenShift 容器平台時,是使用 TCP mode ,Layer 4 的模式,當 HAProxy 收到連線請求時,是直接看哪一個 backend node 可以用,就直接左手給右手,連線到該台 backend node。那 HAProxy 也可以設定為 HTTP mode ,在這種模式下,就像是 nginx/apache 的 reverse proxy ,可以在 frontend 加上憑證跟做 VirtualHost。

安裝很簡單,Ubuntu 跟 RHEL 都有提供

sudo apt install -y haproxy
sudo yum install -y haproxy

安裝以後,設定檔位置是在 /etc/haproxy.cfg

主要需要調整的是 frontend 跟 backend

global
        log /dev/log    local0
        log /dev/log    local1 notice
        chroot /var/lib/haproxy
        stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
        stats timeout 30s
        user haproxy
        group haproxy
        daemon

defaults
        log     global
        mode    http
        option  httplog
        option  dontlognull
        timeout connect 10s
        timeout client  60s
        timeout server  60s
        errorfile 400 /etc/haproxy/errors/400.http
        errorfile 403 /etc/haproxy/errors/403.http
        errorfile 408 /etc/haproxy/errors/408.http
        errorfile 500 /etc/haproxy/errors/500.http
        errorfile 502 /etc/haproxy/errors/502.http
        errorfile 503 /etc/haproxy/errors/503.http
        errorfile 504 /etc/haproxy/errors/504.http

frontend http_bind
        bind *:80
        mode tcp
        option tcplog
        default_backend router_http


frontend https_bind
        bind *:443
        mode tcp
        option tcplog
        default_backend router_https

backend router_http
        mode tcp
        server router_server router:80

backend router_https
        mode tcp
        server router_server router:443

frontend 決定 haproxy 要 listen 哪一個 port,backend 決定是由哪個 node 來處理連線,很容易理解。(聽同事說,這跟 F5 的設定也很接近。)

在 RHEL 會比較容易遇到 HAProxy 有問題,主因是 SELinux ,在啟動 HAProxy 前,需要先使用 setsebool 來設定:

getsebool -a | grep haproxy_connect_any
setsebool haproxy_connect_any on

跟 HAProxy 相關的 SELinux 設定可以用 man 8 haproxy_selinux 來查詢。

參考資料