⚖️
Networking & Server

HAProxy

High availability load balancer and reverse proxy for TCP/HTTP traffic

🐧 Linux🍎 Mac🪟 Windows📋 Quick reference →
Reviewed: Tested on: Kubernetes 1.29 · Terraform 1.8 · Ubuntu 22.04

What is this?

HAProxy spreads incoming web traffic across multiple servers so no single server gets overloaded.

📁

Config files for HAProxy

Where to create or edit the main configuration — paths below match the setup steps.

  • /etc/haproxy/haproxy.cfg

    Location: HAProxy server

    Frontends, backends, ACLs, and SSL

📥

Step 01

Install HAProxy

(01)Install HAProxy

Linux
1# Ubuntu / Debian
2sudo apt-get install -y haproxy
3
4# RHEL / Fedora
5sudo dnf install -y haproxy
6
7sudo systemctl enable haproxy
⚙️

Step 02

Configure HAProxy

(01)HTTP load balancing

Linux
1sudo nano /etc/haproxy/haproxy.cfg
2
3# global / defaults sections first, then:
4
5frontend http_front
6 bind *:80
7 default_backend http_back
8
9backend http_back
10 balance roundrobin
11 server web1 192.168.1.21:80 check
12 server web2 192.168.1.22:80 check
13
14# Stats page (optional):
15listen stats
16 bind *:8404
17 stats enable
18 stats uri /stats
19 stats refresh 10s
20
21sudo haproxy -c -f /etc/haproxy/haproxy.cfg
22sudo systemctl restart haproxy

(02)HTTPS / SSL termination

Linux
1frontend https_front
2 bind *:443 ssl crt /etc/haproxy/certs/example.com.pem
3 default_backend http_back
4
5# Combine cert + key:
6# cat cert.pem key.pem > example.com.pem

(03)TCP (Layer 4) load balancing

Linux
1frontend mysql_front
2 bind *:3306
3 mode tcp
4 default_backend mysql_back
5
6backend mysql_back
7 mode tcp
8 balance leastconn
9 server db1 192.168.1.31:3306 check
10 server db2 192.168.1.32:3306 check

Step 03

Verify HAProxy

(01)Check status

Linux
1sudo systemctl status haproxy
2curl http://localhost/stats
3sudo ss -tlnp | grep haproxy

Step 04

Manage HAProxy

(01)Reload without downtime

Linux
1sudo haproxy -c -f /etc/haproxy/haproxy.cfg
2sudo systemctl reload haproxy
3echo "show stat" | sudo socat stdio /run/haproxy/admin.sock

📋Config templates

1 YAML template for HAProxy. Copy and deploy after setup.

1 ready-to-copy template. Expand one, copy the YAML, then run the deploy commands.

deployment.yml

yaml
1apiVersion: apps/v1
2kind: Deployment
3metadata:
4 name: web
5spec:
6 replicas: 3
7 selector:
8 matchLabels:
9 app: web
10 template:
11 metadata:
12 labels:
13 app: web
14 spec:
15 containers:
16 - name: nginx
17 image: nginx:alpine
18 ports:
19 - containerPort: 80

service-loadbalancer.yml

LoadBalancer assigns external IP (cloud) or MetalLB IP

yaml
1apiVersion: v1
2kind: Service
3metadata:
4 name: web-lb
5spec:
6 type: LoadBalancer
7 selector:
8 app: web
9 ports:
10 - port: 80
11 targetPort: 80
12 protocol: TCP
📄

Step 01

Apply LoadBalancer

(01)Deploy to cluster

Linux
1kubectl apply -f .
2kubectl get all
3kubectl get pods -w

(02)Remove

Linux
1kubectl delete -f .