Setup HAProxy: Load Balancer untuk Aplikasi

HAProxy (High Availability Proxy) adalah salah satu load balancer dan reverse proxy paling populer di dunia Linux. Dia lightweight, cepet, dan reliable buat production environment.

1. Instalasi HAProxy

Ubuntu/Debian:

sudo apt update
sudo apt install haproxy -y

CentOS/RHEL:

sudo yum install haproxy -y
# atau untuk versi baru
sudo dnf install haproxy -y

Verifikasi Instalasi:

haproxy -v

2. Struktur Konfigurasi

File konfigurasi utama ada di:

  • /etc/haproxy/haproxy.cfg

Backup dulu file originalnya bro:

sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.backup

3. Konfigurasi Dasar (HTTP Load Balancing)

Ini contoh setup paling common: load balance 3 backend servers:

# ============================================
# GLOBAL SETTINGS
# ============================================
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

    # Performance tuning
    maxconn 4096
    ulimit-n 8192

# ============================================
# DEFAULTS
# ============================================
defaults
    log global
    mode http
    option httplog
    option dontlognull
    option forwardfor
    option http-server-close
    
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms
    
    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 (Entry Point)
# ============================================
frontend http_front
    bind *:80
    bind *:443 ssl crt /etc/haproxy/certs/your-domain.pem
    
    # Redirect HTTP ke HTTPS
    redirect scheme https if !{ ssl_fc }
    
    # ACL untuk path-based routing (opsional)
    acl is_api path_beg /api
    acl is_static path_beg /static
    
    # Routing rules
    use_backend api_servers if is_api
    use_backend static_servers if is_static
    
    # Default backend
    default_backend web_servers

# ============================================
# BACKENDS (Server Pools)
# ============================================
backend web_servers
    balance roundrobin
    
    # Health checks
    option httpchk GET /health
    http-check expect status 200
    
    # Cookie stickiness (opsional)
    cookie SERVERID insert indirect nocache
    
    # Backend servers
    server web1 192.168.1.10:8080 check cookie web1
    server web2 192.168.1.11:8080 check cookie web2
    server web3 192.168.1.12:8080 check cookie web3 backup

backend api_servers
    balance leastconn
    option httpchk GET /api/health
    
    server api1 192.168.1.20:3000 check
    server api2 192.168.1.21:3000 check

backend static_servers
    balance roundrobin
    server static1 192.168.1.30:80 check

# ============================================
# STATS PAGE (Monitoring Dashboard)
# ============================================
listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 30s
    stats admin if TRUE
    stats auth admin:yourpassword

4. Algoritma Load Balancing

HAProxy support beberapa metode:Table

AlgoritmaKegunaan
roundrobinDefault, distribusi merata per request
leastconnKirim ke server dengan koneksi paling sedikit (bagus untuk long connection seperti WebSocket)
sourceSticky session berdasarkan IP source
uriBerdasarkan URI hash
hdr(<name>)Berdasarkan header tertentu

5. Health Checks

HAProxy punya health check built-in yang powerful:

# Basic TCP check
server web1 192.168.1.10:80 check

# HTTP check dengan interval custom
server web1 192.168.1.10:80 check inter 2000 rise 2 fall 3

# Check dengan expect specific response
option httpchk GET /health
http-check expect status 200
http-check expect string "OK"

Parameter health check:

  • inter 2000 → check tiap 2 detik
  • rise 2 → butuh 2 success buat jadi “up”
  • fall 3 → butuh 3 failure buat jadi “down”

6. SSL/TLS Termination

Generate SSL Certificate (Let’s Encrypt):

sudo certbot certonly --standalone -d yourdomain.com

Combine certificate:

sudo cat /etc/letsencrypt/live/yourdomain.com/fullchain.pem \
    /etc/letsencrypt/live/yourdomain.com/privkey.pem \
    > /etc/haproxy/certs/yourdomain.pem

Konfigurasi di HAProxy:

frontend https_front
    bind *:443 ssl crt /etc/haproxy/certs/yourdomain.pem alpn h2,http/1.1
    
    # SSL configuration
    ssl-default-bind-ciphersuites TLS_AES_128_GCM_SHA256:TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256
    ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets

7. WebSocket Support

Buat app real-time kayak chat atau live updates:

backend websocket_servers
    balance source
    option httpchk GET /health
    
    # WebSocket specific
    http-check send hdr Connection Upgrade hdr Upgrade websocket
    
    server ws1 192.168.1.50:8080 check
    server ws2 192.168.1.51:8080 check

8. Rate Limiting & Security

frontend http_front
    # Stick table untuk tracking
    stick-table type ip size 100k expire 30s store http_req_rate(10s)
    
    # Rate limit: max 10 request per 10 detik per IP
    http-request track-sc0 src
    http-request deny deny_status 429 if { sc_http_req_rate(0) gt 10 }
    
    # Block specific IPs
    acl blocked_ips src 192.168.1.100 10.0.0.50
    http-request deny if blocked_ips
    
    # Security headers
    http-response set-header X-Frame-Options SAMEORIGIN
    http-response set-header X-Content-Type-Options nosniff
    http-response set-header X-XSS-Protection 1;mode=block

9. Monitoring & Stats

Enable Stats Page:

listen stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 5s
    stats show-node
    stats show-desc "Load Balancer Stats"
    stats auth admin:password123
    stats admin if TRUE  # Enable admin commands (disable server, etc)

Akses via: http://your-server:8404/stats

Prometheus Metrics (HAProxy 2.0+):

frontend prometheus
    bind *:8405
    http-request use-service prometheus-exporter if { path /metrics }

10. Testing & Reload

Test konfigurasi:

sudo haproxy -c -f /etc/haproxy/haproxy.cfg

Reload tanpa downtime:

sudo systemctl reload haproxy
# atau
sudo haproxy -sf $(cat /var/run/haproxy.pid)

Start/Stop/Status:

sudo systemctl start haproxy
sudo systemctl stop haproxy
sudo systemctl status haproxy

11. Logging

Setup rsyslog buat HAProxy logs:

# Edit /etc/rsyslog.d/49-haproxy.conf
:programname, startswith, "haproxy" {
    /var/log/haproxy.log
    stop
}

Restart rsyslog:

sudo systemctl restart rsyslog

12. Performance Tuning

Edit /etc/default/haproxy atau systemd service:

# Increase file descriptors
ulimit -n 65536

Di haproxy.cfg:

global
    maxconn 10000
    nbthread 4  # Enable multi-threading (HAProxy 1.8+)

13. Use Case Common

A. Simple Reverse Proxy

frontend main
    bind *:80
    default_backend app

backend app
    server app1 127.0.0.1:3000

B. Multiple Domain (Virtual Hosts)

frontend main
    bind *:80
    
    acl host_app1 hdr(host) -i app1.domain.com
    acl host_app2 hdr(host) -i app2.domain.com
    
    use_backend app1_servers if host_app1
    use_backend app2_servers if host_app2

C. Database Load Balancing (TCP Mode)

frontend mysql_front
    bind *:3306
    mode tcp
    default_backend mysql_servers

backend mysql_servers
    mode tcp
    balance leastconn
    option mysql-check user haproxy_check
    server db1 192.168.1.10:3306 check
    server db2 192.168.1.11:3306 check backup

Tips Production:

  1. Selalu backup config sebelum edit
  2. Test config (-c flag) sebelum reload
  3. Monitor stats page buat lihat traffic distribution
  4. Setup log rotation biar disk nggak penuh
  5. Use backup keyword buat hot standby server
  6. Enable HTTP/2 dengan alpn h2 di SSL bind

Leave a Reply

Your email address will not be published. Required fields are marked *