ตั้งค่า HAProxy Load Balancer บน VPS
HAProxy (High Availability Proxy) คือ load balancer ระดับ production ที่ใช้กันมากที่สุดในโลก รองรับ TCP และ HTTP/HTTPS มี health check อัตโนมัติ, sticky session, SSL termination และ stats dashboard ในตัว เหมาะสำหรับ VPS ที่ต้องการกระจาย traffic ไปหลาย backend server
ติดตั้ง HAProxy
apt update
apt install haproxy -y
haproxy -v
Ubuntu 22.04/24.04 มี HAProxy 2.4+ ให้โดยตรง ถ้าต้องการเวอร์ชันใหม่กว่าสามารถใช้ PPA อย่างเป็นทางการได้:
add-apt-repository ppa:vbernat/haproxy-2.9
apt update
apt install haproxy=2.9.*
โครงสร้างไฟล์ Config
ไฟล์ config หลักอยู่ที่ /etc/haproxy/haproxy.cfg แบ่งเป็น 4 ส่วน:
| Section | หน้าที่ |
|---|---|
global | ตั้งค่า process-level เช่น log, user, maxconn |
defaults | ค่า default ที่ใช้กับทุก frontend/backend |
frontend | รับ incoming connection และ routing rules |
backend | กลุ่ม server ที่รับ traffic จาก frontend |
Config พื้นฐาน: HTTP Load Balancing
# /etc/haproxy/haproxy.cfg
global
log /dev/log local0
log /dev/log local1 notice
chroot /var/lib/haproxy
stats socket /run/haproxy/admin.sock mode 660 level admin
stats timeout 30s
user haproxy
group haproxy
daemon
maxconn 50000
defaults
log global
mode http
option httplog
option dontlognull
option forwardfor
option http-server-close
timeout connect 5s
timeout client 30s
timeout server 30s
errorfile 400 /etc/haproxy/errors/400.http
errorfile 503 /etc/haproxy/errors/503.http
# รับ HTTP port 80
frontend http_front
bind *:80
default_backend web_servers
# กลุ่ม backend servers
backend web_servers
balance roundrobin
option httpchk GET /health
server web1 192.168.1.10:8080 check
server web2 192.168.1.11:8080 check
server web3 192.168.1.12:8080 check
option forwardfor ส่ง X-Forwarded-For header ไปยัง backend เพื่อให้ app รู้ IP จริงของ clientLoad Balancing Algorithms
Round Robin (ค่าเริ่มต้น)
balance roundrobin
server web1 192.168.1.10:8080 check weight 1
server web2 192.168.1.11:8080 check weight 2
# web2 รับ traffic 2 เท่าของ web1
Least Connections
balance leastconn
# ส่งให้ server ที่มี active connection น้อยที่สุด
# เหมาะกับ long-lived connections เช่น WebSocket, database
Source IP Hash (Sticky Sessions)
balance source
hash-type consistent
# Client เดิมจะถูก route ไป server เดิมเสมอ
Health Checks
backend web_servers
balance roundrobin
option httpchk GET /healthz HTTP/1.1\r\nHost:\ localhost
http-check expect status 200
default-server inter 3s fall 3 rise 2
server web1 192.168.1.10:8080 check
server web2 192.168.1.11:8080 check
พารามิเตอร์ health check:
inter 3s— ตรวจสอบทุก 3 วินาทีfall 3— ถ้า fail 3 ครั้งติดกัน ถือว่า server downrise 2— ถ้า success 2 ครั้งติดกัน ถือว่า server กลับมา
SSL Termination
# รวม cert + private key เป็นไฟล์เดียว
cat /etc/ssl/certs/example.crt /etc/ssl/private/example.key > /etc/haproxy/certs/example.pem
chmod 600 /etc/haproxy/certs/example.pem
# Config frontend HTTPS
frontend https_front
bind *:443 ssl crt /etc/haproxy/certs/example.pem
# Redirect HTTP → HTTPS
bind *:80
redirect scheme https code 301 if !{ ssl_fc }
default_backend web_servers
Stats Dashboard
frontend stats
bind *:8404
stats enable
stats uri /stats
stats refresh 10s
stats auth admin:StrongPasswordHere
stats show-legends
stats show-node
เปิด http://your-vps-ip:8404/stats เพื่อดู real-time dashboard แสดง connection count, request rate และสถานะ server แต่ละตัว
Sticky Session ด้วย Cookie
backend web_servers
balance roundrobin
cookie SERVERID insert indirect nocache
server web1 192.168.1.10:8080 check cookie s1
server web2 192.168.1.11:8080 check cookie s2
server web3 192.168.1.12:8080 check cookie s3
HAProxy จะ inject cookie SERVERID เพื่อให้ client กลับมา request ที่ server เดิมเสมอ เหมาะกับ app ที่มี session ใน memory
Rate Limiting
frontend http_front
bind *:80
# สร้าง stick table นับ request ต่อ IP
stick-table type ip size 100k expire 30s store http_req_rate(10s)
http-request track-sc0 src
# Block ถ้า > 100 req ใน 10 วินาที
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 100 }
default_backend web_servers
Reload Config โดยไม่ Drop Connection
# ตรวจสอบ config ก่อน reload
haproxy -c -f /etc/haproxy/haproxy.cfg
# Reload แบบ graceful (zero downtime)
systemctl reload haproxy
ตรวจสอบว่า HAProxy ทำงานถูกต้อง
# ดูสถานะ service
systemctl status haproxy
# ดู active connections
echo "show info" | socat stdio /run/haproxy/admin.sock | grep CurrConns
# ดูสถานะ backend servers ทั้งหมด
echo "show servers state" | socat stdio /run/haproxy/admin.sock
# ทดสอบ load balancing ด้วย curl
for i in {1..6}; do curl -s http://localhost/ | grep "Server:"; done
# ดู log real-time
tail -f /var/log/haproxy.log
socat ด้วย apt install socat เพื่อใช้คำสั่ง admin socket ได้สะดวกแก้ปัญหาที่พบบ่อย
Error: "cannot bind to source address"
เกิดเมื่อ port ที่ HAProxy ต้องการ bind อยู่ระหว่างการ restart ก่อนหน้า ให้ตรวจสอบ:
ss -tlnp | grep :80
# ถ้ามี process อื่นใช้อยู่
kill $(lsof -t -i:80)
systemctl start haproxy
Error: "backend has no server available"
Backend servers ทั้งหมด down หรือ health check fail ตรวจสอบ:
# ดูสถานะ backend
echo "show stat" | socat stdio /run/haproxy/admin.sock | cut -d',' -f1,2,18,19
# ทดสอบ health check endpoint จาก HAProxy server
curl -v http://192.168.1.10:8080/healthz
# ดู log error
journalctl -u haproxy --since "5 minutes ago" | grep -i error
Error: "SSL handshake failure"
มักเกิดจาก PEM file ไม่ถูกต้องหรือ cert หมดอายุ:
# ตรวจสอบ PEM file
openssl x509 -in /etc/haproxy/certs/example.pem -noout -dates
# ตรวจสอบว่า cert และ key match กัน
openssl x509 -noout -modulus -in cert.crt | md5sum
openssl rsa -noout -modulus -in private.key | md5sum
Error: "timeout during connect"
Backend server ไม่ตอบสนองภายในเวลาที่กำหนด ปรับ timeout ใน config:
defaults
timeout connect 10s # เพิ่มจาก 5s
timeout server 60s # เพิ่มสำหรับ slow backend
Error: "haproxy: configuration file has errors"
Syntax error ใน config — ใช้คำสั่ง validate ก่อน reload เสมอ:
haproxy -c -f /etc/haproxy/haproxy.cfg
# ถ้ามี error จะแสดงบรรทัดและคำอธิบาย
คำถามที่พบบ่อย
HAProxy ต่างจาก Nginx/Traefik อย่างไร?
HAProxy เน้น load balancing และ high availability โดยเฉพาะ มี performance สูงมากและ feature ด้าน health check, ACL, และ stats ครบกว่า Nginx เหมาะกับ web server + reverse proxy ส่วน Traefik เน้น auto-discovery ใน container environment HAProxy เหมาะที่สุดสำหรับ production cluster ที่ต้องการ stability
HAProxy รองรับ WebSocket ได้ไหม?
รองรับได้ครับ ใช้ mode http กับ option http-server-close WebSocket จะถูก upgrade เป็น TCP tunnel อัตโนมัติ แต่แนะนำให้ใช้ balance leastconn เพราะ WebSocket เป็น long-lived connection
จะทำ Zero-downtime Deploy ด้วย HAProxy ได้อย่างไร?
ทำได้โดย drain server เก่าก่อน deploy แล้วค่อย enable กลับ: ใช้คำสั่ง echo "disable server web_servers/web1" | socat stdio /run/haproxy/admin.sock deploy บน web1 แล้ว enable server กลับ วนไปจนครบทุก server