HAProxy Advanced Identity Access Management — คู่มือฉบับสมบูรณ์ 2026
โดย อ.บอม กิตติทัศน์ เจริญพนาสิทธิ์ | อัปเดต 24 ก.พ. 2026 | อ่าน 16 นาที
- HAProxy คืออะไร — Load Balancer ระดับโลก
- เปรียบเทียบ HAProxy vs Nginx vs Envoy vs Traefik
- ติดตั้ง HAProxy บน Linux
- พื้นฐาน Configuration — Frontend, Backend, Listen
- Load Balancing Algorithm — เลือกแบบไหนดี
- Health Check — ตรวจสอบ Backend อัตโนมัติ
- SSL/TLS Termination — จัดการ HTTPS
- Identity Access Management (IAM) คืออะไร
- JWT Validation บน HAProxy
- OAuth2 / OIDC Integration
- mTLS — Mutual TLS Authentication
- ACL — Access Control List ขั้นสูง
- Rate Limiting และ DDoS Protection
- High Availability — Active/Passive Failover
- Monitoring และ Stats Dashboard
- Best Practices และสรุป
HAProxy คืออะไร — Load Balancer ระดับโลก
HAProxy (High Availability Proxy) เป็น Open Source Load Balancer และ Reverse Proxy ที่ถูกพัฒนามาตั้งแต่ปี 2000 โดย Willy Tarreau เป็นหนึ่งใน Load Balancer ที่เร็วที่สุดในโลก สามารถรับ Traffic หลายล้าน Concurrent Connection และหลายแสน Request ต่อวินาทีบน Hardware ทั่วไป
HAProxy ถูกใช้งานโดยบริษัทเทคโนโลยีชั้นนำ ได้แก่ GitHub รับ Git Push/Pull ล้านครั้งต่อวัน, Stack Overflow กระจาย Traffic ไปยัง Web Server หลายตัว, Reddit จัดการ Traffic จาก User หลายร้อยล้านคน, Airbnb เป็น API Gateway สำหรับ Microservices และ Instagram ใช้เป็น Internal Load Balancer
จุดเด่นของ HAProxy เหนือ Load Balancer อื่นคือ Performance ที่สูงมาก ใช้ Event-driven Architecture เหมือน Nginx, Health Check ที่ละเอียดมาก ตรวจได้ทั้ง TCP, HTTP, Custom Script, Connection Draining ที่ค่อยๆ ปิด Connection เก่าก่อน Remove Backend, Stats Dashboard ในตัว ดู Traffic แบบ Real-time และ ACL ที่ทรงพลัง กำหนดเงื่อนไข Routing ซับซ้อนได้
เปรียบเทียบ HAProxy vs Nginx vs Envoy vs Traefik
| คุณสมบัติ | HAProxy | Nginx | Envoy | Traefik |
|---|---|---|---|---|
| Load Balancing | ดีเยี่ยม | ดีมาก | ดีมาก | ดี |
| Web Server | ไม่ใช่ | ดีเยี่ยม | ไม่ใช่ | ไม่ใช่ |
| Health Check | ละเอียดมาก | Basic (Plus ดีกว่า) | ละเอียด | Basic |
| Service Discovery | DNS/Consul | DNS | xDS API | Auto (Docker/K8s) |
| Config Reload | Seamless | Seamless | Hot Restart | Auto |
| Learning Curve | ปานกลาง | ง่าย | สูง | ง่าย |
| เหมาะกับ | Pure LB/Gateway | Web + LB | Service Mesh | Docker/K8s |
ติดตั้ง HAProxy บน Linux
# Ubuntu / Debian — ติดตั้งเวอร์ชันล่าสุดจาก PPA
sudo add-apt-repository ppa:vbernat/haproxy-2.9 -y
sudo apt update
sudo apt install haproxy -y
# Rocky Linux / AlmaLinux
sudo dnf install haproxy -y
# ตรวจสอบเวอร์ชัน
haproxy -v
# HAProxy version 2.9.x
# เปิดใช้งาน
sudo systemctl enable --now haproxy
# ตรวจ Config ก่อน Reload
haproxy -c -f /etc/haproxy/haproxy.cfg
พื้นฐาน Configuration — Frontend, Backend, Listen
HAProxy Config แบ่งเป็น 4 ส่วนหลัก global ตั้งค่าทั่วไป เช่น Log, Performance Tuning, defaults ค่า Default สำหรับทุก Frontend/Backend, frontend รับ Traffic จาก Client (Bind Port, ACL, Routing) และ backend กำหนด Server ปลายทาง (Load Balance Algorithm, Health Check)
# /etc/haproxy/haproxy.cfg
global
log /dev/log local0
maxconn 50000
user haproxy
group haproxy
daemon
# Performance Tuning
tune.ssl.default-dh-param 2048
ssl-default-bind-options ssl-min-ver TLSv1.2
ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5s
timeout client 30s
timeout server 30s
retries 3
option redispatch
frontend http_front
bind *:80
bind *:443 ssl crt /etc/ssl/certs/siamcafe.pem
# Redirect HTTP to HTTPS
http-request redirect scheme https unless { ssl_fc }
# Route to Backend
default_backend web_servers
backend web_servers
balance roundrobin
option httpchk GET /health
http-check expect status 200
server web1 192.168.1.10:8080 check inter 5s fall 3 rise 2
server web2 192.168.1.11:8080 check inter 5s fall 3 rise 2
server web3 192.168.1.12:8080 check inter 5s fall 3 rise 2
Load Balancing Algorithm — เลือกแบบไหนดี
| Algorithm | วิธีทำงาน | เหมาะกับ |
|---|---|---|
| roundrobin | วนส่งทีละตัว ตามน้ำหนัก | Workload ทั่วไป (Default) |
| leastconn | ส่งไป Server ที่ Connection น้อยที่สุด | Long Connection เช่น WebSocket, DB |
| source | Hash จาก Source IP ส่งไป Server เดิม | Session Persistence แบบง่าย |
| uri | Hash จาก URI ส่ง URL เดิมไป Server เดิม | Cache Server |
| hdr(name) | Hash จาก HTTP Header ที่ระบุ | Route ตาม Header เช่น X-Tenant-ID |
| random | สุ่ม Server แบบ Random | Large Cluster ที่ต้องการ Even Distribution |
Health Check — ตรวจสอบ Backend อัตโนมัติ
HAProxy มี Health Check ที่ละเอียดมาก ตรวจได้หลายระดับ
# TCP Health Check (ตรวจแค่ Port เปิด)
server web1 192.168.1.10:8080 check
# HTTP Health Check (ตรวจ HTTP Response)
option httpchk GET /health
http-check expect status 200
server web1 192.168.1.10:8080 check
# Advanced HTTP Health Check (ตรวจ Body)
option httpchk
http-check send meth GET uri /health ver HTTP/1.1 hdr Host www.example.com
http-check expect rstring "status.*ok"
# Parameters:
# inter 5s = ตรวจทุก 5 วินาที
# fall 3 = ล้มเหลว 3 ครั้งถือว่า Down
# rise 2 = สำเร็จ 2 ครั้งถือว่า Up
# slowstart 30s = ค่อยๆ เพิ่ม Traffic หลัง Recovery
server web1 192.168.1.10:8080 check inter 5s fall 3 rise 2 slowstart 30s
SSL/TLS Termination — จัดการ HTTPS
HAProxy สามารถทำ SSL/TLS Termination ได้ รับ HTTPS จาก Client แล้วส่ง HTTP ไป Backend ลดภาระ Backend Server จากการ Encrypt/Decrypt
# SSL Termination
frontend https_front
bind *:443 ssl crt /etc/ssl/certs/siamcafe.pem alpn h2,http/1.1
# HSTS Header
http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains"
# Forward Client IP
option forwardfor
http-request set-header X-Forwarded-Proto https
default_backend web_servers
# SSL Passthrough (ไม่ Decrypt ส่ง TCP ตรงไป Backend)
frontend tcp_front
bind *:443
mode tcp
tcp-request inspect-delay 5s
tcp-request content accept if { req_ssl_hello_type 1 }
use_backend sni_backend if { req.ssl_sni -i api.example.com }
default_backend default_ssl
Identity Access Management (IAM) คืออะไร
Identity Access Management (IAM) เป็นระบบจัดการตัวตนและสิทธิ์การเข้าถึงทรัพยากร ประกอบด้วย 2 ส่วนหลัก Authentication (AuthN) ยืนยันว่าคุณเป็นใคร เช่น Username/Password, OAuth2 Token, Client Certificate และ Authorization (AuthZ) ตรวจว่าคุณมีสิทธิ์ทำอะไร เช่น RBAC, ABAC, Policy-based
HAProxy สามารถทำหน้าที่เป็น IAM Gateway ได้โดยตรวจสอบ Identity ของ Request ก่อนส่ง Traffic ไป Backend ทำให้ Backend ไม่ต้องจัดการ Authentication เอง เป็น Centralized Auth Point เดียวสำหรับทุก Microservice
JWT Validation บน HAProxy
HAProxy 2.4+ รองรับ JWT Verification ในตัว สามารถตรวจสอบ JWT Token จาก Authorization Header ก่อนส่ง Request ไป Backend
# JWT Validation ด้วย HAProxy
frontend api_front
bind *:443 ssl crt /etc/ssl/certs/api.pem
# ดึง JWT Token จาก Authorization: Bearer xxx
http-request set-var(txn.token) req.hdr(Authorization),word(2," ")
# Verify JWT (ใช้ Lua Script)
http-request lua.verify_jwt
# Deny ถ้า JWT ไม่ถูกต้อง
http-request deny deny_status 401 unless { var(txn.jwt_valid) -m bool }
# ส่ง JWT Claims ไป Backend เป็น Header
http-request set-header X-User-ID %[var(txn.jwt_sub)]
http-request set-header X-User-Role %[var(txn.jwt_role)]
# Route ตาม Role
use_backend admin_servers if { var(txn.jwt_role) -m str admin }
default_backend api_servers
# หรือใช้ External Auth Service (SPOE)
frontend api_front
bind *:443 ssl crt /etc/ssl/certs/api.pem
# ส่ง Token ไป Auth Service ตรวจสอบ
filter spoe engine auth-check config /etc/haproxy/spoe-auth.conf
http-request deny deny_status 401 unless { var(sess.auth.is_valid) -m bool }
OAuth2 / OIDC Integration
สำหรับ OAuth2 / OpenID Connect (OIDC) HAProxy ทำหน้าที่เป็น Resource Server ที่ตรวจสอบ Access Token กับ Authorization Server (เช่น Keycloak, Auth0, Okta)
# OAuth2 Token Introspection
# HAProxy ส่ง Token ไปตรวจกับ Auth Server
frontend api_front
bind *:443 ssl crt /etc/ssl/certs/api.pem
# ดึง Bearer Token
http-request set-var(txn.bearer) req.hdr(Authorization),word(2," ")
# เรียก Auth Server Introspection Endpoint
http-request set-header X-Auth-Token %[var(txn.bearer)]
# ใช้ SPOE เรียก Auth Service
filter spoe engine oauth2 config /etc/haproxy/spoe-oauth2.conf
# ตรวจผลลัพธ์
http-request deny deny_status 401 if !{ var(sess.oauth2.active) -m bool }
http-request deny deny_status 403 if !{ var(sess.oauth2.scope) -m sub "read:api" }
default_backend api_servers
mTLS — Mutual TLS Authentication
mTLS (Mutual TLS) คือการที่ทั้ง Client และ Server ตรวจ Certificate ซึ่งกันและกัน เหมาะสำหรับ Service-to-Service Authentication ใน Microservices หรือ API ที่ต้องการความปลอดภัยสูง
# mTLS Configuration
frontend mtls_front
bind *:8443 ssl crt /etc/ssl/certs/server.pem ca-file /etc/ssl/certs/ca.pem verify required
# ดึงข้อมูลจาก Client Certificate
http-request set-header X-Client-CN %[ssl_c_s_dn(cn)]
http-request set-header X-Client-OU %[ssl_c_s_dn(ou)]
http-request set-header X-Client-Serial %[ssl_c_serial,hex]
# Route ตาม Client Certificate CN
use_backend payment_backend if { ssl_c_s_dn(cn) -m str payment-service }
use_backend order_backend if { ssl_c_s_dn(cn) -m str order-service }
# Deny ถ้า Certificate ไม่อยู่ใน Whitelist
http-request deny deny_status 403 unless { ssl_c_s_dn(cn) -m str -f /etc/haproxy/allowed-clients.lst }
default_backend default_backend
ACL — Access Control List ขั้นสูง
ACL เป็นจุดแข็งของ HAProxy ที่ให้กำหนดเงื่อนไข Routing และ Access Control ได้ซับซ้อนมาก
# ACL ตัวอย่าง
frontend http_front
bind *:443 ssl crt /etc/ssl/certs/site.pem
# ACL ตาม Path
acl is_api path_beg /api/
acl is_admin path_beg /admin/
acl is_static path_end .css .js .png .jpg .svg
# ACL ตาม Header
acl is_mobile req.hdr(User-Agent) -i -m sub mobile
acl has_api_key req.hdr(X-API-Key) -m found
# ACL ตาม Source IP
acl is_internal src 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
acl is_blocked src -f /etc/haproxy/blocked-ips.lst
# ACL ตาม Method
acl is_write method POST PUT DELETE PATCH
# ACL ตาม Time
acl is_maintenance_window date_hour 2 3 4
# ใช้ ACL กำหนด Rules
http-request deny if is_blocked
http-request deny deny_status 403 if is_admin !is_internal
http-request deny deny_status 401 if is_api !has_api_key
http-request deny deny_status 503 if is_maintenance_window is_write
# Routing ตาม ACL
use_backend api_servers if is_api
use_backend admin_servers if is_admin is_internal
use_backend static_servers if is_static
default_backend web_servers
Rate Limiting และ DDoS Protection
# Rate Limiting ด้วย Stick Tables
frontend http_front
bind *:443 ssl crt /etc/ssl/certs/site.pem
# นับ Request ต่อ IP (Stick Table)
stick-table type ip size 100k expire 30s store http_req_rate(10s)
http-request track-sc0 src
# Block ถ้าเกิน 100 Request ใน 10 วินาที
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 100 }
# Rate Limit ต่อ API Key
stick-table type string len 64 size 100k expire 60s store http_req_rate(60s)
http-request track-sc1 req.hdr(X-API-Key)
http-request deny deny_status 429 if { sc_http_req_rate(1) gt 1000 }
# Slowdown แทน Block (Tarpit)
http-request tarpit if { sc_http_req_rate(0) gt 200 }
default_backend web_servers
High Availability — Active/Passive Failover
HAProxy เองก็ต้องมี HA เพื่อไม่ให้เป็น Single Point of Failure ใช้ Keepalived จัดการ Virtual IP (VIP) ระหว่าง HAProxy 2 ตัว
# /etc/keepalived/keepalived.conf (Master)
vrrp_script chk_haproxy {
script "/usr/bin/killall -0 haproxy"
interval 2
weight 2
}
vrrp_instance VI_1 {
state MASTER
interface eth0
virtual_router_id 51
priority 101
advert_int 1
authentication {
auth_type PASS
auth_pass mypassword
}
virtual_ipaddress {
192.168.1.100/24
}
track_script {
chk_haproxy
}
}
เมื่อ HAProxy Master ล่ม Keepalived จะย้าย VIP ไป Backup Server อัตโนมัติภายใน 2-3 วินาที Client ไม่รู้ด้วยซ้ำว่า Failover เกิดขึ้น
Monitoring และ Stats Dashboard
# เปิด Stats Dashboard
listen stats
bind *:8404
mode http
stats enable
stats uri /stats
stats refresh 10s
stats admin if LOCALHOST
stats auth admin:secretpassword
# Prometheus Exporter (Built-in ตั้งแต่ 2.4)
frontend prometheus
bind *:8405
mode http
http-request use-service prometheus-exporter if { path /metrics }
Stats Dashboard แสดง Traffic, Connection, Error Rate, Backend Health แบบ Real-time Prometheus Metrics ส่งเข้า Grafana สร้าง Dashboard สวยงามได้
Best Practices และสรุป
- ใช้ HAProxy เป็น Centralized Auth Gateway — ตรวจ JWT/OAuth2/mTLS ที่จุดเดียว Backend ไม่ต้องจัดการเอง
- Health Check ต้องละเอียด — อย่าแค่ตรวจ Port เปิด ต้องตรวจ HTTP Response และ Body
- ใช้ Stick Table สำหรับ Rate Limit — ป้องกัน DDoS และ Abuse ที่ Edge
- HA ด้วย Keepalived — HAProxy ต้องมีอย่างน้อย 2 ตัวเสมอ
- Monitor ด้วย Prometheus + Grafana — ติดตาม Connection, Error Rate, Latency แบบ Real-time
- Config Version Control — เก็บ Config ใน Git ผ่าน Code Review ก่อน Deploy
- Test Config ก่อน Reload — ใช้
haproxy -c -fทุกครั้งก่อน Reload - ใช้ Seamless Reload — HAProxy Reload ไม่ Drop Connection ใช้ได้อย่างปลอดภัย
HAProxy เป็น Load Balancer ที่ทรงพลังที่สุดตัวหนึ่งในโลก Open Source เมื่อรวมกับ Identity Access Management ทำให้เป็นทั้ง Gateway, Auth Proxy และ Traffic Manager ในตัวเดียว ลดความซับซ้อนของ Microservices Architecture ได้อย่างมาก ติดตามบทความใหม่ๆ ได้ที่ SiamCafe.net
คำถามที่พบบ่อย (FAQ)
Q: HAProxy คืออะไร
Open Source Load Balancer และ Reverse Proxy ที่เร็วมาก รับ Traffic หลายล้าน Connection ใช้โดย GitHub, Stack Overflow, Reddit
Q: HAProxy ต่างจาก Nginx อย่างไร
HAProxy เชี่ยวชาญ Load Balancing มี Health Check ละเอียดกว่า ส่วน Nginx เก่งทั้ง Web Server + Reverse Proxy มี Caching ในตัว หลายองค์กรใช้ร่วมกัน
Q: HAProxy ทำ JWT Validation ได้อย่างไร
HAProxy 2.4+ มี Built-in JWT Support ใช้ร่วมกับ Lua Script หรือ SPOE สำหรับ Verify Signature ตรวจ Expiry และ Claims ก่อนส่งไป Backend
Q: mTLS คืออะไร
Mutual TLS ทั้ง Client และ Server ตรวจ Certificate ซึ่งกันและกัน เหมาะกับ Service-to-Service Auth ใน Microservices กำหนดด้วย verify required ใน HAProxy
Q: Rate Limiting บน HAProxy ทำอย่างไร
ใช้ Stick Table นับ Request ต่อ IP หรือ API Key แล้ว Deny ด้วย 429 เมื่อเกิน Threshold หรือใช้ Tarpit ชะลอแทน Block