For our Blog Visitor only Get Additional 3 Month Free + 10% OFF on TriAnnual Plan YSBLOG10
Grab the Deal

How to Configure HAProxy on Linux Server – (Step-by-Step Guide 2026)

To configure HAProxy on a Linux server, install the haproxy package, back up /etc/haproxy/haproxy.cfg, define global/defaults, create a frontend (bind 80/443), add backends with servers and health checks, validate with haproxy -c, enable the service, open the firewall, and monitor logs and the stats page. Below is a complete 2026-ready guide.

This step-by-step guide shows how to configure HAProxy on Linux for reliable load balancing, SSL termination, health checks, routing with ACLs, and rate limiting. Whether you’re using Ubuntu, Debian, Rocky Linux, AlmaLinux, or RHEL, you’ll learn production-ready patterns, secure defaults, and troubleshooting tips from real-world hosting experience.

What Is HAProxy and Why Use It on Linux?

haproxy3

HAProxy (High Availability Proxy) is a fast, open-source load balancer and reverse proxy for TCP and HTTP(S). On Linux, it distributes traffic across multiple application servers, improves availability, enables zero-downtime maintenance, and adds features like SSL offload, sticky sessions, path/host-based routing, and DDoS rate limiting.

Who This Guide Is For

Beginners configuring their first Linux load balancer, sysadmins migrating from Nginx/Apache proxies, and SREs modernizing infrastructure. We’ll use simple language and include ready-to-paste configuration examples you can adapt for 2026 best practices.

Prerequisites and Lab Topology

Before you configure HAProxy on Linux, ensure you have:

  • A Linux server (Ubuntu 22.04/24.04, Debian 12, Rocky/AlmaLinux 9, or RHEL 9)
  • Root or sudo access
  • Two or more backend app servers (e.g., 10.0.0.11 and 10.0.0.12)
  • Domain name (for SSL) pointing to the HAProxy server’s IP
  • Firewall control (ufw or firewalld)

Ports to open: 80 (HTTP), 443 (HTTPS), and optionally 8404 for the HAProxy stats page.

Ubuntu/Debian

sudo apt update
sudo apt install -y haproxy
haproxy -v

Rocky Linux / AlmaLinux / RHEL

sudo dnf install -y haproxy
haproxy -v

Back up the default configuration:

sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak.$(date +%F)

Create a Minimal, Secure HAProxy Configuration (HTTP Only)

Start with a clean, production-friendly base. Replace backend IPs with your servers.

sudo tee /etc/haproxy/haproxy.cfg >/dev/null <<'CFG'
global
  log /dev/log local0
  log /dev/log local1 notice
  chroot /var/lib/haproxy
  user haproxy
  group haproxy
  daemon
  stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
  stats timeout 30s
  maxconn 50000
  tune.ssl.default-dh-param 2048

defaults
  log     global
  mode    http
  option  httplog
  option  dontlognull
  option  http-keep-alive
  timeout connect 5s
  timeout client  30s
  timeout server  30s
  default-server inter 3s fall 3 rise 2

frontend http-in
  bind :80
  default_backend app-backend

backend app-backend
  balance roundrobin
  option httpchk GET /health
  http-check expect status 200
  server app1 10.0.0.11:8080 check
  server app2 10.0.0.12:8080 check

listen stats
  bind :8404
  stats enable
  stats uri /stats
  stats refresh 10s
  stats auth admin:StrongPass!
CFG

Validate, Enable, and Open the Firewall

# Validate configuration syntax
sudo haproxy -c -f /etc/haproxy/haproxy.cfg

# Enable and start HAProxy
sudo systemctl enable --now haproxy
sudo systemctl status haproxy --no-pager

# Ubuntu/Debian firewall (ufw)
sudo ufw allow 80,443,8404/tcp

# RHEL family (firewalld)
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --permanent --add-port=8404/tcp
sudo firewall-cmd --reload

Visit http://your-domain-or-ip/stats, authenticate, and confirm both servers are healthy.

Add HTTPS/SSL Termination (Let’s Encrypt)

We’ll obtain a certificate and terminate TLS in HAProxy. The simplest approach uses Certbot’s standalone mode, briefly stopping HAProxy during issuance and renewal.

# Install Certbot (Ubuntu example via snap)
sudo apt install -y snapd
sudo snap install core
sudo snap install --classic certbot
sudo ln -s /snap/bin/certbot /usr/bin/certbot

# Prepare cert directory for HAProxy
sudo mkdir -p /etc/haproxy/certs
sudo chown -R root:root /etc/haproxy/certs
sudo chmod 700 /etc/haproxy/certs

# Issue certificate (replace example.com and email)
sudo systemctl stop haproxy
sudo certbot certonly --standalone -d example.com -d www.example.com \
  --email admin@example.com --agree-tos --non-interactive

# Concatenate fullchain + key into HAProxy PEM
sudo bash -c 'cat /etc/letsencrypt/live/example.com/fullchain.pem \
  /etc/letsencrypt/live/example.com/privkey.pem > /etc/haproxy/certs/example.com.pem'
sudo chmod 600 /etc/haproxy/certs/example.com.pem
sudo systemctl start haproxy

Update HAProxy to redirect HTTP to HTTPS and bind TLS with ALPN and HSTS:

sudo sed -n '1,200p' /etc/haproxy/haproxy.cfg > /tmp/haproxy.part

sudo tee /etc/haproxy/haproxy.cfg >/dev/null <<'CFG'
global
  log /dev/log local0
  log /dev/log local1 notice
  chroot /var/lib/haproxy
  user haproxy
  group haproxy
  daemon
  stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
  stats timeout 30s
  maxconn 50000
  tune.ssl.default-dh-param 2048

defaults
  log     global
  mode    http
  option  httplog
  option  dontlognull
  option  http-keep-alive
  timeout connect 5s
  timeout client  30s
  timeout server  30s
  default-server inter 3s fall 3 rise 2

frontend http-in
  bind :80
  redirect scheme https code 301 if !{ ssl_fc }

frontend https-in
  bind :443 ssl crt /etc/haproxy/certs/example.com.pem alpn h2,http/1.1
  http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
  default_backend app-backend

backend app-backend
  balance roundrobin
  option httpchk GET /health
  http-check expect status 200
  server app1 10.0.0.11:8080 check
  server app2 10.0.0.12:8080 check

listen stats
  bind :8404
  stats enable
  stats uri /stats
  stats refresh 10s
  stats auth admin:StrongPass!
CFG

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

Automate renewals with a deploy hook to rebuild the PEM and reload HAProxy:

sudo bash -c 'cat > /etc/letsencrypt/renewal-hooks/deploy/haproxy.sh' <<'H'
#!/usr/bin/env bash
set -e
DOM="example.com"
cat /etc/letsencrypt/live/$DOM/fullchain.pem /etc/letsencrypt/live/$DOM/privkey.pem \
  > /etc/haproxy/certs/$DOM.pem
chmod 600 /etc/haproxy/certs/$DOM.pem
systemctl reload haproxy
H
sudo chmod +x /etc/letsencrypt/renewal-hooks/deploy/haproxy.sh

Choose Load-Balancing Algorithms and Health Checks

Common algorithms:

  • roundrobin – even distribution (default)
  • leastconn – favors servers with fewer active connections
  • source – consistent hashing by client IP (simple stickiness)

Example with least connections and robust health checks:

backend api-backend
  balance leastconn
  option httpchk GET /healthz
  http-check expect status 200
  server api1 10.0.0.21:8000 check
  server api2 10.0.0.22:8000 check

Enable Sticky Sessions (Session Persistence)

For stateful apps, enable cookie-based stickiness so a user remains on the same server:

backend app-backend
  balance roundrobin
  cookie SRV insert indirect nocache
  option httpchk GET /health
  server app1 10.0.0.11:8080 check cookie s1
  server app2 10.0.0.12:8080 check cookie s2

Advanced Routing with ACLs (Path/Host-Based)

Route APIs and static content to dedicated pools using ACLs:

frontend https-in
  bind :443 ssl crt /etc/haproxy/certs/example.com.pem alpn h2,http/1.1
  acl is_api path_beg /api
  acl img_host hdr(host) -i img.example.com
  use_backend api-backend if is_api
  use_backend img-backend if img_host
  default_backend app-backend

Backends can then be tuned specifically for their workloads (e.g., caching headers for images).

Rate Limiting and Basic DDoS Protection

Use stick-tables to deny excessive requests gracefully with HTTP 429:

frontend https-in
  bind :443 ssl crt /etc/haproxy/certs/example.com.pem alpn h2,http/1.1
  stick-table type ip size 100k expire 10m store http_req_rate(10s)
  http-request track-sc0 src
  acl too_fast sc_http_req_rate(0) gt 100
  http-request deny status 429 if too_fast
  default_backend app-backend

Adjust thresholds to your traffic profile. Combine with network-level rate limits where possible.

Logging and Monitoring

Enable and Read Logs

Default configs log via /dev/log. Check system logs and HAProxy’s unit:

journalctl -u haproxy -f
sudo tail -f /var/log/syslog   # Debian/Ubuntu
sudo tail -f /var/log/messages # RHEL/Rocky/AlmaLinux

Stats Page and Metrics

Visit https://your-domain:8404/stats for a live dashboard. For Prometheus/Grafana, use haproxy-exporter or HAProxy’s native Prometheus stats when available in your version.

High Availability with VRRP (Keepalived)

Create an active-passive HA pair using a floating virtual IP:

# Install keepalived
sudo apt install -y keepalived   # Debian/Ubuntu
# sudo dnf install -y keepalived # RHEL family

# Example /etc/keepalived/keepalived.conf (Primary)
vrrp_instance VI_1 {
  state MASTER
  interface eth0
  virtual_router_id 51
  priority 200
  advert_int 1
  authentication {
    auth_type PASS
    auth_pass 7XyZ1234
  }
  virtual_ipaddress {
    10.0.0.100/24
  }
}

Use the same config on the secondary but with state BACKUP and lower priority. Point DNS to the virtual IP for seamless failover.

Performance and Security Best Practices

  • OS tuning: raise file descriptors and backlog limits (use systemd override for HAProxy: LimitNOFILE=100000).
  • TLS: enable TLS 1.2/1.3 only; prefer modern ciphers; enable HSTS as shown.
  • Health checks: use fast, lightweight endpoints (e.g., /health returning 200).
  • Observability: centralize logs, enable stats, and scrape metrics.
  • Change management: test with haproxy -c and reload gracefully (systemctl reload haproxy).
  • Access control: password-protect /stats, restrict by IP if needed.
  • Backups: version-control haproxy.cfg; keep PEMs secure (600 permissions).

Troubleshooting Common Issues

  • Port already in use: check with sudo ss -ltnp | grep -E ‘:80|:443’.
  • Bad certificate chain: ensure fullchain.pem and key concatenation order is correct for PEM.
  • Backends marked down: verify health URL, firewall, and app port (curl -I http://10.0.0.11:8080/health).
  • HTTP/2 not negotiating: confirm alpn h2,http/1.1 on bind and that client supports H2.
  • Slow responses: review logs for retries/timeouts and consider leastconn or server capacity.

Automate Configuration with Ansible (Optional)

---
- hosts: haproxy
  become: true
  tasks:
    - name: Install HAProxy
      package:
        name: haproxy
        state: present
    - name: Deploy haproxy.cfg
      copy:
        src: files/haproxy.cfg
        dest: /etc/haproxy/haproxy.cfg
        owner: root
        group: root
        mode: '0644'
      notify: reload haproxy
    - name: Ensure service is enabled
      service:
        name: haproxy
        state: started
        enabled: true
  handlers:
    - name: reload haproxy
      service:
        name: haproxy
        state: reloaded

Managed vs. Self-Managed: When to Get Help

If you’d rather not maintain certificates, failover, and continuous tuning, consider a managed option. At YouStable, our cloud servers and managed stacks can ship with pre-hardened HAProxy, SSL automation, health monitoring, and 24×7 support—so you focus on the app while we handle the edge.

Complete Reference Configuration (HTTPS, ACLs, Sticky, Stats)

global
  log /dev/log local0
  log /dev/log local1 notice
  chroot /var/lib/haproxy
  user haproxy
  group haproxy
  daemon
  stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
  stats timeout 30s
  maxconn 50000
  tune.ssl.default-dh-param 2048

defaults
  log     global
  mode    http
  option  httplog
  option  dontlognull
  option  http-keep-alive
  timeout connect 5s
  timeout client  30s
  timeout server  30s
  default-server inter 3s fall 3 rise 2

frontend http-in
  bind :80
  redirect scheme https code 301 if !{ ssl_fc }

frontend https-in
  bind :443 ssl crt /etc/haproxy/certs/example.com.pem alpn h2,http/1.1
  http-response set-header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"

  # Basic rate limiting
  stick-table type ip size 100k expire 10m store http_req_rate(10s)
  http-request track-sc0 src
  acl too_fast sc_http_req_rate(0) gt 100
  http-request deny status 429 if too_fast

  # Routing rules
  acl is_api path_beg /api
  use_backend api-backend if is_api

  default_backend app-backend

backend app-backend
  balance roundrobin
  cookie SRV insert indirect nocache
  option httpchk GET /health
  http-check expect status 200
  server app1 10.0.0.11:8080 check cookie s1
  server app2 10.0.0.12:8080 check cookie s2

backend api-backend
  balance leastconn
  option httpchk GET /healthz
  http-check expect status 200
  server api1 10.0.0.21:8000 check
  server api2 10.0.0.22:8000 check

listen stats
  bind :8404
  stats enable
  stats uri /stats
  stats refresh 10s
  stats auth admin:StrongPass!

FAQs: Configure HAProxy on Linux (2026)

What is HAProxy used for on a Linux server?

HAProxy is used as a load balancer and reverse proxy to distribute client traffic across multiple backend servers, improve availability, enable SSL offload, enforce routing policies, and provide observability via logs and a stats interface.

Is HAProxy Layer 4 or Layer 7?

Both. In TCP mode it operates at Layer 4 (useful for databases, SMTP, etc.). In HTTP mode it operates at Layer 7, enabling path/host-based routing, header rewrites, and content-aware features.

How do I enable SSL in HAProxy?

Obtain a certificate (e.g., with Certbot), concatenate fullchain.pem and privkey.pem into a single PEM, reference it in bind :443 ssl crt /path/to/cert.pem, and redirect HTTP to HTTPS. Reload HAProxy and verify with an SSL test.

How can I check HAProxy health and logs?

Use journalctl -u haproxy -f to follow service logs, check /var/log/syslog or /var/log/messages depending on distro, and monitor the stats page at /stats. You can also scrape metrics via a Prometheus exporter.

HAProxy vs Nginx for load balancing—which should I choose?

Both are excellent. HAProxy excels in advanced LB features, health checks, stick-tables, and extensive routing logic. Nginx is strong as a web server with proxy features. For pure load balancing at scale, HAProxy is often preferred.

You now have a secure, production-ready way to configure HAProxy on Linux with HTTPS, health checks, ACL routing, sticky sessions, and basic rate limiting. Iterate safely by testing configs, reloading, and observing metrics—then scale out backends with confidence. If you need a managed setup, YouStable can help you deploy and operate it end-to-end.

Prahlad Prajapati

Prahlad is a web hosting specialist and SEO-focused organic growth expert from India. Active in the digital space since 2019, he helps people grow their websites through clean, sustainable strategies. Passionate about learning and adapting fast, he believes small details create big success. Discover his insights on web hosting and SEO to elevate your online presence.

Leave a Comment

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

Scroll to Top