How to Install and Configure HAProxy as a Load Balancer on an Ubuntu VPS
As websites and applications grow, relying on a single server can create performance bottlenecks, scalability limitations, and availability risks.
HAProxy is a high-performance, open-source load balancer and reverse proxy that distributes incoming network traffic across multiple backend servers.
By deploying HAProxy on an Ubuntu VPS, you can distribute application workloads, automatically detect unavailable backend servers, terminate HTTPS connections, and perform backend maintenance without necessarily interrupting access to your application.
In this tutorial, you will learn how to install and configure HAProxy as a load balancer on an Ubuntu VPS, including HTTP and TCP load balancing, HTTPS termination, backend health checks, session persistence, traffic monitoring, rate limiting, security hardening, and configuration rollback.
This guide is suitable for Ubuntu 22.04 LTS, Ubuntu 24.04 LTS, Ubuntu 26.04 LTS, and other supported Linux distributions with compatible HAProxy packages.
Prerequisites
- An Ubuntu VPS with root or sudo access to act as the load balancer.
- Two or more backend servers running a compatible website or application.
- Network connectivity between the load balancer and backend servers.
- A domain name pointing to the load balancer for public web applications.
- SSH or remote console access to each server.
- A verified backup of existing application and server configurations.
- Basic familiarity with Linux networking and web servers.
A single VPS can also be used to test HAProxy by running multiple backend application instances on different local ports.
However, deploying all components on the same VPS does not provide protection against failure of that VPS.
1. What Is HAProxy?
HAProxy stands for High Availability Proxy. It is an open-source software load balancer designed to distribute TCP and HTTP connections across multiple backend services.
HAProxy is commonly used for:
- Website and application load balancing.
- HTTP and HTTPS reverse proxying.
- API gateway infrastructure.
- Database connection routing.
- Microservices and containerized applications.
- Backend health monitoring.
- Traffic distribution across multiple VPS servers.
- Application maintenance and controlled traffic migration.
- TLS termination and TLS passthrough.
A basic HAProxy deployment looks like this:
Internet
|
v
HAProxy Load Balancer
|
+-----------+-----------+
| | |
v v v
Web VPS 1 Web VPS 2 Web VPS 3
Instead of connecting directly to an application server, visitors connect to HAProxy, which selects an appropriate backend server according to its configuration.
2. Understand Layer 4 and Layer 7 Load Balancing
HAProxy supports both Layer 4 and Layer 7 load balancing.
| Feature | Layer 4 | Layer 7 |
|---|---|---|
| HAProxy mode | TCP | HTTP |
| Traffic awareness | TCP connections | HTTP requests and responses |
| URL-based routing | No | Yes |
| HTTP header inspection | No | Yes |
| HTTP cookie persistence | No | Yes |
| TLS passthrough | Yes | Not in ordinary HTTP mode |
| Typical workloads | Databases, TCP services, encrypted connections | Websites, REST APIs, HTTP applications |
Layer 4 load balancing operates primarily at the transport layer and does not need to understand the application protocol.
Layer 7 load balancing understands HTTP and can make routing decisions based on hostnames, URL paths, headers, cookies, and other HTTP attributes.
For most websites and web applications, Layer 7 load balancing provides greater flexibility.
3. HAProxy vs. Nginx vs. Varnish
| Software | Primary Strength |
|---|---|
| HAProxy | Advanced TCP and HTTP load balancing, health checks, and traffic management |
| Nginx | Web serving, reverse proxying, load balancing, and caching |
| Varnish Cache | High-performance HTTP response caching |
| Apache | Flexible web application hosting and extensible HTTP server functionality |
| Keepalived | Virtual IP management and network-level failover in compatible environments |
These technologies can complement one another.
For example, HAProxy can distribute incoming traffic across several Nginx web servers, each running PHP-FPM and a local caching mechanism.
4. Example Multi-VPS Architecture
This tutorial uses the following illustrative server configuration:
| Server | Private IP Address | Purpose |
|---|---|---|
| lb01 | 10.10.10.10 | HAProxy load balancer |
| web01 | 10.10.10.11 | First web server |
| web02 | 10.10.10.12 | Second web server |
| web03 | 10.10.10.13 | Optional third web server |
The public domain used throughout this tutorial is:
example.com
Replace all example hostnames and IP addresses with the actual values assigned to your infrastructure.
The private IP addresses shown above assume that private networking or a secure overlay network has already been configured between the VPS servers.
Private networking availability depends on your hosting environment. If private connectivity is unavailable, consider a secure WireGuard or equivalent encrypted network between the servers.
5. Understand Application Requirements Before Load Balancing
Adding a load balancer does not automatically make an application horizontally scalable.
Before distributing traffic across multiple servers, determine how the application manages:
- User authentication and sessions.
- Database connections.
- Uploaded files and media.
- Application configuration.
- Encryption and signing keys.
- Background jobs and scheduled tasks.
- Application cache invalidation.
- Software updates and deployment consistency.
For example, if a user uploads a file to web01, that file must also be available when a subsequent request is processed by web02.
Similarly, if application sessions are stored only in local files, a user may lose their session when HAProxy selects a different backend server.
Shared databases, distributed session storage, synchronized files, and consistent application deployments may be required.
6. Prepare the Backend Web Servers
For a simple demonstration, install Nginx on both backend VPS servers.
Run the following commands on web01 and web02:
sudo apt update
sudo apt install -y nginx
sudo systemctl enable --now nginx
On web01, create a temporary demonstration page:
echo 'Response from web01' |
sudo tee /var/www/html/index.html
On web02:
echo 'Response from web02' |
sudo tee /var/www/html/index.html
These commands are intended for new demonstration servers.
Do not overwrite the document root of an existing production website.
For production deployments, retain your existing application and web server configuration.
7. Create Backend Health Check Endpoints
HAProxy can periodically request a dedicated HTTP endpoint to determine whether a backend server is available.
On each demonstration web server, create a static health check file:
echo 'OK' | sudo tee /var/www/html/healthz
Test the endpoint locally:
curl -i http://127.0.0.1/healthz
Expected response:
HTTP/1.1 200 OK
OK
A static health endpoint confirms that the web server can serve an HTTP response.
It does not necessarily confirm that PHP-FPM, the database, or other application dependencies are functioning correctly.
For production applications, consider implementing a dedicated readiness endpoint that verifies essential dependencies without exposing sensitive system information.
Avoid expensive database queries or resource-intensive operations inside frequently requested health endpoints.
8. Verify Network Connectivity
From the HAProxy VPS, test connectivity to each backend:
curl --connect-timeout 5 http://10.10.10.11/
curl --connect-timeout 5 http://10.10.10.12/
Expected output:
Response from web01
Response from web02
Test the health endpoints:
curl -i --connect-timeout 5 http://10.10.10.11/healthz
curl -i --connect-timeout 5 http://10.10.10.12/healthz
If connectivity fails, verify routing, firewall rules, listening addresses, and the backend web server status.
Do not proceed until HAProxy can communicate reliably with each intended backend.
9. Inspect the Load Balancer VPS
Check the operating system:
cat /etc/os-release
uname -r
Check available resources:
free -h
nproc
df -hT
Inspect active network listeners:
sudo ss -ltnp
Check whether the intended public ports are already in use:
sudo ss -ltnp |
grep -E ':(80|443|8404)\b'
If Nginx, Apache, or another service already occupies ports 80 or 443, determine how the existing service will be migrated before enabling HAProxy on those ports.
Do not stop an existing production web server without a documented transition and rollback plan.
10. Install HAProxy on Ubuntu
Update the package index:
sudo apt update
Check the available package version:
apt-cache policy haproxy
Install HAProxy:
sudo apt install -y haproxy
Verify the installed version:
haproxy -v
Display detailed build information:
haproxy -vv
Inspect the service:
sudo systemctl status haproxy --no-pager
Inspect the installed systemd service definition:
sudo systemctl cat haproxy
Available HAProxy features and configuration directives can vary between package versions.
Always validate configuration files against the version installed on your VPS.
11. Create a Timestamped Configuration Backup
Before modifying HAProxy, create a recoverable configuration backup.
Enter a root shell:
sudo -i
Create the backup:
BACKUP="/root/haproxy-backup-$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP"
chmod 700 "$BACKUP"
cp -a /etc/haproxy "$BACKUP/"
systemctl cat haproxy > "$BACKUP/haproxy-systemd.txt"
sha256sum "$BACKUP/haproxy/haproxy.cfg" \
> "$BACKUP/SHA256SUMS"
echo "Backup directory: $BACKUP"
Verify the backup:
sha256sum -c "$BACKUP/SHA256SUMS"
Record the backup directory for future rollback.
Exit the root shell if desired:
exit
12. Understand HAProxy Configuration Sections
The main HAProxy configuration file on Ubuntu is normally:
/etc/haproxy/haproxy.cfg
HAProxy configurations commonly contain the following sections:
| Section | Purpose |
|---|---|
global |
Process-wide settings, logging, runtime sockets, and resource limits |
defaults |
Default settings inherited by subsequent proxy sections |
frontend |
Incoming connections, listening addresses, and routing decisions |
backend |
Backend servers, load balancing algorithms, and health checks |
listen |
A combined frontend and backend definition |
userlist |
Authentication users and groups |
peers |
Synchronization of supported stick-table data between HAProxy instances |
Understanding these sections makes it easier to maintain and expand your configuration.
13. Configure Basic HTTP Load Balancing
Open the HAProxy configuration file:
sudo nano /etc/haproxy/haproxy.cfg
The following is a complete example configuration for a dedicated HAProxy VPS distributing HTTP traffic across two backend web servers:
global
log /dev/log local0
log /dev/log local1 notice
user haproxy
group haproxy
maxconn 2000
stats socket /run/haproxy/admin.sock mode 660 level admin
stats timeout 30s
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5s
timeout client 30s
timeout server 30s
timeout http-request 10s
timeout http-keep-alive 10s
timeout queue 30s
timeout check 3s
frontend public_http
bind *:80
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto http
default_backend web_servers
backend web_servers
balance roundrobin
option httpchk
http-check send meth GET uri /healthz ver HTTP/1.1 hdr Host example.com
http-check expect status 200
default-server inter 3s fall 3 rise 2
server web01 10.10.10.11:80 check
server web02 10.10.10.12:80 check
listen local_stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
stats refresh 10s
stats hide-version
This configuration provides:
- Public HTTP listening on port 80.
- Round-robin traffic distribution.
- HTTP backend health checks.
- Automatic removal of unhealthy servers from normal traffic distribution.
- Controlled connection and request timeouts.
- Original client IP forwarding.
- A local administrative runtime socket.
- A statistics dashboard restricted to localhost.
The example assumes a new dedicated load balancer. Preserve any package-specific or application-specific settings required by an existing installation.
14. Validate the HAProxy Configuration
Always validate the configuration before applying it:
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
Expected output:
Configuration file is valid
If HAProxy reports an error, correct the indicated configuration line before restarting or reloading the service.
Configuration validation checks syntax and supported directives. It does not guarantee that the backend applications are reachable or that application behavior is correct.
15. Start and Enable HAProxy
Apply the initial configuration:
sudo systemctl restart haproxy
sudo systemctl enable haproxy
Verify the service:
sudo systemctl status haproxy --no-pager
Inspect recent logs:
sudo journalctl -u haproxy -n 50 --no-pager
Verify listening ports:
sudo ss -ltnp | grep haproxy
HAProxy should listen publicly on port 80 and locally on port 8404.
16. Test Load Balancing
From the load balancer VPS, run several requests:
for i in $(seq 1 10); do
curl -sS -H 'Host: example.com' http://127.0.0.1/
done
Illustrative output:
Response from web01
Response from web02
Response from web01
Response from web02
Response from web01
Response from web02
The exact request distribution can vary depending on connection reuse, backend health, concurrency, persistence settings, and the selected load balancing algorithm.
Both backend servers should receive traffic when they are healthy.
17. Understand HAProxy Load Balancing Algorithms
| Algorithm | Behavior | Typical Use |
|---|---|---|
roundrobin |
Distributes traffic across available servers according to their weights | General-purpose web applications |
leastconn |
Prefers servers with fewer active connections | Long-lived or variable-duration connections |
source |
Uses the client source address to select a backend | Basic source-based persistence |
uri |
Uses the HTTP request URI to select a backend | Specialized cache-oriented architectures |
first |
Prefers available servers according to server order and capacity | Consolidating traffic onto fewer servers |
Round-robin is a suitable starting point for many ordinary HTTP applications.
Least-connections can be useful when requests or connections have substantially different durations.
The best algorithm depends on actual workload characteristics.
18. Configure Least-Connections Load Balancing
To use least-connections, modify the backend:
backend web_servers
balance leastconn
option httpchk
http-check send meth GET uri /healthz ver HTTP/1.1 hdr Host example.com
http-check expect status 200
default-server inter 3s fall 3 rise 2
server web01 10.10.10.11:80 check
server web02 10.10.10.12:80 check
Validate and reload:
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && \
sudo systemctl reload haproxy
Use monitoring data to determine whether the new algorithm improves traffic distribution and backend resource utilization.
19. Configure Weighted Load Balancing
Backend servers do not need to have identical hardware resources.
For example, web01 may have twice the processing capacity of web02.
Configure relative weights:
backend web_servers
balance roundrobin
option httpchk
http-check send meth GET uri /healthz ver HTTP/1.1 hdr Host example.com
http-check expect status 200
default-server inter 3s fall 3 rise 2
server web01 10.10.10.11:80 check weight 200
server web02 10.10.10.12:80 check weight 100
Under appropriate conditions, web01 will receive approximately twice the traffic assigned to web02.
Weights are relative values, not guaranteed percentages.
Monitor CPU utilization, memory usage, response times, and application throughput before selecting production weights.
20. Configure Backend Health Checks
The example configuration uses:
default-server inter 3s fall 3 rise 2
These settings control backend health detection:
| Parameter | Meaning |
|---|---|
inter 3s |
Normal health check interval |
fall 3 |
Consecutive failed checks required to mark a server down |
rise 2 |
Consecutive successful checks required to mark a server healthy again |
timeout check 3s |
Health check response timeout |
Actual detection time depends on check scheduling, connection timeouts, response timeouts, and the current backend state.
Do not assume that a failed server will be removed at an exact fixed number of seconds.
Very aggressive health checks can increase backend workload or cause unnecessary state changes during temporary network congestion.
21. Test Automatic Backend Failover
Perform this test only on demonstration servers or during an approved maintenance window.
On web01, temporarily stop Nginx:
sudo systemctl stop nginx
Wait for HAProxy to detect the failed health checks.
From the load balancer, run:
for i in $(seq 1 10); do
curl -sS -H 'Host: example.com' http://127.0.0.1/
sleep 1
done
Once web01 has been marked unavailable, new eligible requests should be routed to web02.
Restore web01:
sudo systemctl start nginx
After the configured successful health checks, HAProxy should return web01 to normal traffic distribution.
Existing connections or requests interrupted by a backend failure may still fail. Health checks do not guarantee that every in-flight request survives a server outage.
22. Configure a Backup Server
HAProxy supports backend servers that receive traffic only when ordinary active servers are unavailable.
For example:
backend web_servers
balance roundrobin
option httpchk
http-check send meth GET uri /healthz ver HTTP/1.1 hdr Host example.com
http-check expect status 200
default-server inter 3s fall 3 rise 2
server web01 10.10.10.11:80 check
server web02 10.10.10.12:80 check
server web03 10.10.10.13:80 check backup
In this configuration, web03 acts as a standby backend.
It is normally selected only when the ordinary active backend servers are unavailable, subject to the configured persistence and backend behavior.
The backup server must have access to the same application data and configuration required to serve production traffic.
23. Configure DNS for the Load Balancer
For a public website, configure the domain to resolve to the public IP address of the HAProxy VPS.
Example DNS record:
| Type | Name | Value |
|---|---|---|
| A | @ | Public IPv4 address of HAProxy VPS |
If IPv6 is supported and configured on the load balancer, you may also create an AAAA record.
Do not publish an AAAA record unless the IPv6 listener, routing, and firewall configuration are operational.
Install DNS troubleshooting utilities if necessary:
sudo apt install -y dnsutils
Verify DNS resolution:
dig +short A example.com
dig +short AAAA example.com
For existing production websites, consider reducing the DNS TTL in advance of the migration.
Retain the previous DNS configuration until the new load balancer has been verified.
24. Understand HTTPS Termination
HAProxy can terminate TLS connections directly when built with the required SSL support.
With TLS termination, visitors connect to HAProxy using HTTPS. HAProxy decrypts the request and forwards it to the selected backend.
Internet Visitors
|
| HTTPS
v
HAProxy :443
|
| HTTP or HTTPS
|
+-------------------+
| |
v v
web01 web02
TLS termination allows HAProxy to inspect HTTP requests, apply URL-based routing, manage HTTP cookies, and enforce application-level traffic policies.
If backend traffic crosses an untrusted network, use verified backend TLS or an encrypted private network rather than transmitting sensitive application data over unencrypted HTTP.
25. Install Certbot
Install Certbot to obtain a Let's Encrypt certificate:
sudo apt update
sudo apt install -y certbot
Verify installation:
certbot --version
The domain must resolve to the correct public endpoint before requesting a certificate using HTTP-01 validation.
Ensure that inbound TCP port 80 is reachable from the internet.
26. Configure Certificate Validation Without Stopping HAProxy
Certbot standalone mode normally requires an available listening port for the ACME HTTP challenge.
Rather than stopping HAProxy for every renewal, configure a dedicated local challenge listener on port 8888.
First, verify that the port is available:
sudo ss -ltnp | grep ':8888\b'
Modify the public HTTP frontend:
frontend public_http
bind *:80
acl acme_challenge path_beg /.well-known/acme-challenge/
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto http
use_backend acme_backend if acme_challenge
default_backend web_servers
Add the following backend:
backend acme_backend
mode http
server certbot 127.0.0.1:8888
Do not configure ordinary health checks on this backend because Certbot only listens during certificate validation.
Validate and reload HAProxy:
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && \
sudo systemctl reload haproxy
Request the certificate:
sudo certbot certonly \
--standalone \
--preferred-challenges http \
--http-01-address 127.0.0.1 \
--http-01-port 8888 \
-d example.com
Replace example.com with your actual domain.
Certbot listens locally on port 8888, while the certificate authority connects to the public HAProxy listener on port 80.
HAProxy forwards the ACME challenge request to Certbot.
If a CDN or external reverse proxy is present, ensure that ACME challenge requests reach the correct origin without being blocked or incorrectly cached.
27. Prepare the TLS Certificate for HAProxy
HAProxy commonly uses a PEM file containing both the certificate chain and its corresponding private key.
Create a protected certificate directory:
sudo install -d -m 700 /etc/haproxy/certs
Combine the certificate chain and private key:
sudo bash -c '
umask 077
cat /etc/letsencrypt/live/example.com/fullchain.pem \
/etc/letsencrypt/live/example.com/privkey.pem \
> /etc/haproxy/certs/example.com.pem
'
Restrict permissions:
sudo chmod 600 /etc/haproxy/certs/example.com.pem
sudo chown root:root /etc/haproxy/certs/example.com.pem
Inspect the certificate without displaying its private key:
sudo openssl x509 \
-in /etc/haproxy/certs/example.com.pem \
-noout -subject -issuer -dates
Verify the certificate hostname and expiration date before continuing.
The standard root-started HAProxy service can normally load the certificate before dropping privileges. If your service uses a different privilege model, adjust permissions according to that model without making private keys publicly readable.
28. Configure HTTPS Termination in HAProxy
Replace the existing public HTTP frontend with:
frontend public_http
bind *:80
acl acme_challenge path_beg /.well-known/acme-challenge/
acl valid_host hdr(host) -i example.com example.com:80
http-request deny deny_status 403 unless valid_host
http-request redirect scheme https code 301 unless acme_challenge
use_backend acme_backend if acme_challenge
default_backend web_servers
Add a public HTTPS frontend:
frontend public_https
bind *:443 ssl crt /etc/haproxy/certs/example.com.pem ssl-min-ver TLSv1.2 alpn h2,http/1.1
acl valid_host hdr(host) -i example.com example.com:443
http-request deny deny_status 403 unless valid_host
http-request set-header Host example.com
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto https
http-request set-header X-Forwarded-Port 443
http-request set-header X-Forwarded-Host example.com
default_backend web_servers
Retain the ACME backend:
backend acme_backend
mode http
server certbot 127.0.0.1:8888
Retain the existing web_servers backend and local statistics listener.
This configuration assumes a single canonical website hostname.
If additional domains or aliases are required, configure their certificates, hostname validation, and routing explicitly.
Validate the configuration:
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
Apply the configuration:
sudo systemctl reload haproxy
Verify the HTTPS listener:
sudo ss -ltnp | grep ':443\b'
29. Test HTTPS and HTTP Redirection
Test the public HTTPS endpoint:
curl -I https://example.com/
Test HTTP redirection:
curl -I http://example.com/
Expected HTTP response:
HTTP/1.1 301 Moved Permanently
location: https://example.com/
Inspect the certificate presented by HAProxy:
openssl s_client \
-connect example.com:443 \
-servername example.com \
-verify_hostname example.com \
-verify_return_error \
< /dev/null
Verify that the certificate is trusted, valid, and issued for the intended hostname.
To test the local load balancer before changing public DNS, use:
curl --resolve example.com:443:127.0.0.1 \
https://example.com/
This preserves the expected HTTP hostname and TLS Server Name Indication while connecting directly to the local HAProxy listener.
30. Automate HAProxy Certificate Renewal
Certbot can automatically renew Let's Encrypt certificates, but HAProxy must also receive the updated combined PEM file.
Create a deploy hook directory:
sudo mkdir -p /etc/letsencrypt/renewal-hooks/deploy
Create the deploy hook:
sudo nano /etc/letsencrypt/renewal-hooks/deploy/haproxy-example-com.sh
Add the following script:
#!/usr/bin/env bash
set -Eeuo pipefail
DOMAIN="example.com"
LINEAGE="/etc/letsencrypt/live/$DOMAIN"
CERT_DIR="/etc/haproxy/certs"
DEST="$CERT_DIR/$DOMAIN.pem"
CFG="/etc/haproxy/haproxy.cfg"
if [[ "${RENEWED_LINEAGE:-}" != "$LINEAGE" ]]; then
exit 0
fi
umask 077
install -d -m 700 "$CERT_DIR"
TMP=$(mktemp "$CERT_DIR/.$DOMAIN.XXXXXX")
BACKUP_DIR="/root/haproxy-cert-backups"
install -d -m 700 "$BACKUP_DIR"
BACKUP="$BACKUP_DIR/$DOMAIN.pem.$(date +%Y%m%d-%H%M%S).$$"
trap 'rm -f "$TMP"' EXIT
cat "$LINEAGE/fullchain.pem" \
"$LINEAGE/privkey.pem" > "$TMP"
chmod 600 "$TMP"
openssl x509 -in "$TMP" -noout -checkend 0
CERT_PUB=$(
openssl x509 -in "$TMP" -pubkey -noout |
openssl pkey -pubin -outform DER |
sha256sum
)
KEY_PUB=$(
openssl pkey -in "$TMP" -pubout -outform DER |
sha256sum
)
if [[ "$CERT_PUB" != "$KEY_PUB" ]]; then
echo "Certificate and private key do not match." >&2
exit 1
fi
if [[ ! -f "$DEST" ]]; then
echo "Existing HAProxy certificate not found: $DEST" >&2
exit 1
fi
cp -a "$DEST" "$BACKUP"
mv -f "$TMP" "$DEST"
if ! haproxy -c -f "$CFG"; then
cp -a "$BACKUP" "$DEST"
echo "Configuration validation failed. Certificate restored." >&2
exit 1
fi
if ! systemctl reload haproxy; then
cp -a "$BACKUP" "$DEST"
if ! systemctl reload haproxy; then
echo "CRITICAL: HAProxy rollback reload failed." >&2
fi
exit 1
fi
if ! systemctl is-active --quiet haproxy; then
cp -a "$BACKUP" "$DEST"
systemctl reload haproxy || true
echo "HAProxy service verification failed." >&2
exit 1
fi
echo "HAProxy certificate updated successfully."
echo "Previous certificate backup: $BACKUP"
Replace the DOMAIN value with your actual domain.
Make the script executable:
sudo chmod 700 \
/etc/letsencrypt/renewal-hooks/deploy/haproxy-example-com.sh
Validate the script syntax:
sudo bash -n \
/etc/letsencrypt/renewal-hooks/deploy/haproxy-example-com.sh
Test the Certbot renewal process:
sudo certbot renew --dry-run
Certbot dry-run testing does not normally execute deploy hooks unless explicitly requested using the appropriate option.
To test the deployment hook using the currently installed production certificate:
sudo env \
RENEWED_LINEAGE=/etc/letsencrypt/live/example.com \
/etc/letsencrypt/renewal-hooks/deploy/haproxy-example-com.sh
This test performs a real HAProxy reload and creates a certificate backup. Run it during an appropriate maintenance period.
Check the automatic renewal schedule:
systemctl list-timers --all | grep certbot
Certificate backups contain private keys. Keep them protected and establish a retention policy for obsolete backups.
After renewal, independently verify the certificate presented by the public HTTPS endpoint.
31. Preserve the Original Visitor IP Address
Without additional configuration, backend servers may see the HAProxy IP address instead of the original visitor IP address.
The public frontend in this tutorial overwrites the X-Forwarded-For header:
http-request set-header X-Forwarded-For %[src]
This prevents ordinary clients from supplying an arbitrary forwarding header that would be trusted by the backend.
On each Nginx backend, configure trusted real-IP processing:
set_real_ip_from 10.10.10.10;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
Add these directives to an appropriate Nginx HTTP or server configuration context.
Validate and reload Nginx:
sudo nginx -t && sudo systemctl reload nginx
For Apache backends, enable the remote IP module:
sudo a2enmod remoteip
Configure the trusted load balancer address:
RemoteIPHeader X-Forwarded-For
RemoteIPInternalProxy 10.10.10.10
Validate and reload Apache:
sudo apache2ctl configtest && \
sudo systemctl reload apache2
Only trust forwarding headers from explicitly authorized reverse proxies.
If HAProxy itself is behind Cloudflare or another CDN, the direct connection source may be the CDN rather than the original visitor. Configure CDN-specific client IP handling using verified trusted proxy networks.
32. Configure WordPress Behind HAProxy
When HAProxy terminates HTTPS and forwards HTTP requests to a WordPress backend, WordPress must correctly recognize the original connection scheme.
HAProxy sets:
http-request set-header X-Forwarded-Proto https
For a WordPress backend accessible only through the trusted load balancer, the application may need to interpret this header.
For example, add the following to wp-config.php before WordPress initialization:
if (
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https'
) {
$_SERVER['HTTPS'] = 'on';
}
Use this approach only when backend network access is restricted to trusted infrastructure and the forwarding header is overwritten by the load balancer.
Verify that the WordPress Address and Site Address use the intended public HTTPS hostname.
For a multi-server WordPress deployment, also ensure:
- All application servers use the same WordPress database.
- WordPress authentication salts are consistent.
- Uploaded media is available to every backend.
- Plugin and theme versions remain synchronized.
- Object caching is configured consistently.
- Scheduled jobs are coordinated where necessary.
- Page cache invalidation is handled across all servers.
HAProxy distributes requests but does not synchronize WordPress files or databases.
33. Configure Cookie-Based Session Persistence
Some applications require a visitor to continue using the same backend server across multiple requests.
HAProxy can implement cookie-based persistence in HTTP mode.
Modify the backend:
backend web_servers
balance roundrobin
cookie SERVERID insert indirect nocache httponly secure
option httpchk
http-check send meth GET uri /healthz ver HTTP/1.1 hdr Host example.com
http-check expect status 200
default-server inter 3s fall 3 rise 2
server web01 10.10.10.11:80 check cookie web01
server web02 10.10.10.12:80 check cookie web02
The secure cookie attribute assumes that visitors access the application using HTTPS.
Validate and reload HAProxy:
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && \
sudo systemctl reload haproxy
Test cookie persistence:
COOKIE_JAR=$(mktemp)
for i in $(seq 1 5); do
curl -sS \
-c "$COOKIE_JAR" \
-b "$COOKIE_JAR" \
https://example.com/
done
rm -f "$COOKIE_JAR"
Requests using the same persistence cookie should normally continue to reach the associated available backend.
If that backend fails, HAProxy may select another server.
Cookie persistence does not replicate application sessions or guarantee that session data survives backend failure.
34. Configure Source-IP Persistence
For workloads where cookie-based persistence is unsuitable, source-based load balancing can provide basic client affinity.
backend web_servers
balance source
option httpchk
http-check send meth GET uri /healthz ver HTTP/1.1 hdr Host example.com
http-check expect status 200
default-server inter 3s fall 3 rise 2
server web01 10.10.10.11:80 check
server web02 10.10.10.12:80 check
Requests from the same source IP will generally map to the same available backend under stable backend conditions.
However, source-IP persistence has limitations:
- Many users may share a single NAT gateway.
- Corporate networks may concentrate traffic behind a few IP addresses.
- Mobile clients may change IP addresses.
- CDNs and reverse proxies may obscure the original source.
- Backend availability changes may alter server selection.
For scalable web applications, shared session storage is generally preferable to depending entirely on source-IP persistence.
35. Configure Hostname-Based Routing
HAProxy can route different domain names to different backend applications.
For example:
example.com -> website backend
api.example.com -> API backend
app.example.com -> application backend
A representative HTTPS frontend is:
frontend public_https
bind *:443 ssl crt /etc/haproxy/certs/ ssl-min-ver TLSv1.2 alpn h2,http/1.1
acl host_website hdr(host) -i example.com example.com:443
acl host_api hdr(host) -i api.example.com api.example.com:443
acl host_app hdr(host) -i app.example.com app.example.com:443
http-request deny deny_status 403 unless host_website or host_api or host_app
http-request set-header X-Forwarded-For %[src]
http-request set-header X-Forwarded-Proto https
use_backend api_servers if host_api
use_backend app_servers if host_app
default_backend web_servers
Define the additional backends:
backend api_servers
balance leastconn
server api01 10.10.10.21:8080 check
server api02 10.10.10.22:8080 check
backend app_servers
balance roundrobin
server app01 10.10.10.31:8080 check
server app02 10.10.10.32:8080 check
The additional backend examples use basic TCP connectivity checks.
For production applications, configure appropriate application-specific HTTP readiness checks.
Each public hostname must have a valid matching TLS certificate.
Update the HTTP frontend and ACME certificate validation configuration to support the additional hostnames as well.
36. Configure URL Path-Based Routing
HAProxy can route requests based on URL paths.
For example:
https://example.com/ -> website
https://example.com/api/ -> API
https://example.com/media/ -> media service
Add the following routing rules to the appropriate HTTP frontend:
acl path_api path -i /api
acl path_api path_beg -i /api/
acl path_media path -i /media
acl path_media path_beg -i /media/
use_backend api_servers if path_api
use_backend media_servers if path_media
default_backend web_servers
Define the media backend:
backend media_servers
balance roundrobin
server media01 10.10.10.41:8080 check
server media02 10.10.10.42:8080 check
HAProxy forwards the original request path unless an explicit rewrite rule is configured.
Ensure each backend application understands the URL paths it receives.
37. Configure Backend HTTPS Encryption
For environments where HAProxy-to-backend traffic must also be encrypted, configure TLS on the backend servers.
A representative backend configuration is:
backend secure_web_servers
balance roundrobin
option httpchk
http-check send meth GET uri /healthz ver HTTP/1.1 hdr Host example.com
http-check expect status 200
default-server inter 3s fall 3 rise 2
server web01 10.10.10.11:443 check ssl verify required ca-file /etc/ssl/certs/ca-certificates.crt verifyhost web01.internal.example.com sni str(web01.internal.example.com) check-sni web01.internal.example.com
server web02 10.10.10.12:443 check ssl verify required ca-file /etc/ssl/certs/ca-certificates.crt verifyhost web02.internal.example.com sni str(web02.internal.example.com) check-sni web02.internal.example.com
Each backend must present a certificate trusted by HAProxy and matching the configured verification hostname.
If you use an internal certificate authority, replace the CA file with the appropriate trusted CA certificate bundle.
Configure the public HTTPS frontend to use secure_web_servers when this backend is ready.
Do not use verify none as a routine solution for certificate validation failures.
Encryption without server identity verification can leave backend connections vulnerable to interception.
38. Configure TCP Load Balancing
HAProxy can also distribute ordinary TCP connections.
For example, the following configuration creates a TCP listener on an internal address:
frontend internal_tcp
bind 10.10.10.10:9000
mode tcp
option tcplog
timeout client 5m
default_backend tcp_servers
backend tcp_servers
mode tcp
balance leastconn
timeout connect 5s
timeout server 5m
server tcp01 10.10.10.51:9000 check
server tcp02 10.10.10.52:9000 check
This example assumes that the load balancer owns the private IP address 10.10.10.10.
TCP mode does not provide ordinary HTTP header manipulation, URL-based routing, or HTTP cookie persistence.
Use application-specific health checks where supported and appropriate.
For database workloads, remember that distributing connections does not automatically provide database replication, transaction consistency, or primary-node election.
39. Configure TLS Passthrough
TLS passthrough allows encrypted client connections to reach backend servers without HAProxy terminating TLS.
Internet
|
| Encrypted TLS
v
HAProxy TCP Listener
|
| Encrypted TLS
v
Backend TLS Server
For a dedicated TLS passthrough deployment, a representative configuration is:
frontend tls_passthrough
bind *:443
mode tcp
option tcplog
timeout client 5m
default_backend tls_servers
backend tls_servers
mode tcp
balance roundrobin
timeout connect 5s
timeout server 5m
server web01 10.10.10.11:443 check
server web02 10.10.10.12:443 check
Each backend server must provide a valid TLS certificate for the public website hostname.
Important: This frontend is an alternative to the HTTPS termination frontend previously configured on port 443.
Do not configure both frontends to bind to the same address and port.
Basic TCP health checks confirm that the backend accepts connections. They do not necessarily confirm that the backend certificate or application response is valid.
40. Configure TLS SNI-Based Routing
For some TLS passthrough deployments, HAProxy can inspect the visible Server Name Indication in the TLS ClientHello and route the connection accordingly.
Example:
frontend tls_passthrough
bind *:443
mode tcp
option tcplog
tcp-request inspect-delay 5s
tcp-request content accept if { req.ssl_hello_type 1 }
acl sni_website req.ssl_sni -i example.com
acl sni_api req.ssl_sni -i api.example.com
use_backend website_tls if sni_website
use_backend api_tls if sni_api
default_backend rejected_tls
backend website_tls
mode tcp
balance roundrobin
server web01 10.10.10.11:443 check
server web02 10.10.10.12:443 check
backend api_tls
mode tcp
balance leastconn
server api01 10.10.10.21:443 check
server api02 10.10.10.22:443 check
backend rejected_tls
mode tcp
tcp-request content reject
This approach depends on the required SNI information being visible to HAProxy.
Clients that do not provide a usable SNI value, including some configurations using encrypted ClientHello, may not be routable according to this policy.
Test compatibility with the actual clients and TLS architecture before production deployment.
41. Configure WebSocket Support
HAProxy can proxy WebSocket connections in HTTP mode.
Applications using WebSockets often require longer tunnel timeouts than ordinary HTTP requests.
Add an appropriate tunnel timeout to the relevant backend or defaults section:
timeout tunnel 1h
For example:
backend websocket_servers
mode http
balance leastconn
timeout tunnel 1h
server ws01 10.10.10.61:8080 check
server ws02 10.10.10.62:8080 check
Route the relevant WebSocket application path or hostname to this backend.
HAProxy can handle ordinary HTTP/1.1 WebSocket upgrade requests without manually inserting upgrade headers.
Validate compatibility with your application protocol and HAProxy version.
Long-lived WebSocket connections consume resources on both the load balancer and backend servers.
42. Configure HAProxy Connection Limits
Connection limits help protect the load balancer and backend applications from excessive concurrent workloads.
The global example configuration includes:
maxconn 2000
You can also define limits for individual frontends:
frontend public_https
bind *:443 ssl crt /etc/haproxy/certs/example.com.pem
maxconn 1500
default_backend web_servers
This snippet illustrates the additional maxconn directive. Preserve all existing TLS, hostname validation, and forwarding rules when applying it.
Backend server limits can be configured individually:
server web01 10.10.10.11:80 check maxconn 200
server web02 10.10.10.12:80 check maxconn 200
When backend capacity is reached, HAProxy may queue eligible requests according to its configuration.
The queue timeout determines how long a request can wait for an available backend connection.
timeout queue 30s
Connection limits should reflect measured application capacity rather than arbitrary high values.
43. Configure Basic HTTP Rate Limiting
HAProxy stick tables can track request rates and apply basic traffic restrictions.
Add the following directives to the public HTTPS frontend:
stick-table type ip size 100k expire 30s store http_req_rate(10s)
http-request track-sc0 src
http-request deny deny_status 429 if { sc_http_req_rate(0) gt 100 }
This example tracks the HTTP request rate associated with each source IP address over a ten-second period.
Requests exceeding the configured threshold receive HTTP 429 Too Many Requests.
The threshold is illustrative and must be adjusted for the application.
Web pages containing many assets, API clients, shared corporate networks, and legitimate automation may generate substantial request rates.
If HAProxy is behind a CDN, tracking the direct connection source may group many unrelated visitors under a CDN IP address.
Configure trusted client IP handling before applying source-based restrictions in that architecture.
Rate limiting can help protect application resources, but it does not replace upstream DDoS mitigation for attacks that saturate the VPS network connection.
44. Configure Endpoint-Specific Rate Limiting
Some application endpoints require more restrictive policies than ordinary public pages.
For example, WordPress login requests can be tracked separately using a dedicated stick table.
Define a tracking backend:
backend login_rate_table
stick-table type ip size 100k expire 60s store http_req_rate(60s)
Add the following directives to the public HTTPS frontend:
acl wordpress_login path -i /wp-login.php
http-request track-sc1 src table login_rate_table if wordpress_login
http-request deny deny_status 429 if wordpress_login { sc_http_req_rate(1) gt 20 }
This example limits repeated requests to the WordPress login endpoint independently of the general frontend request rate.
The threshold must be tested against legitimate login behavior.
For applications with authenticated APIs or shared client networks, consider application-aware limits instead of relying exclusively on source IP addresses.
45. Configure HAProxy Statistics
HAProxy includes a built-in statistics dashboard that provides operational information about frontends, backends, and individual servers.
The main example configuration includes:
listen local_stats
bind 127.0.0.1:8404
mode http
stats enable
stats uri /stats
stats refresh 10s
stats hide-version
The dashboard is restricted to localhost.
From the HAProxy VPS, test it:
curl -I http://127.0.0.1:8404/stats
To access the dashboard securely from your workstation, create an SSH tunnel:
ssh -N -L 8404:127.0.0.1:8404 admin@LOAD_BALANCER_IP
Replace the username and server IP with your actual SSH connection details.
Open the following address in your local browser:
http://127.0.0.1:8404/stats
The SSH tunnel provides encrypted access without exposing the statistics dashboard directly to the public internet.
46. Understand HAProxy Statistics
The HAProxy statistics dashboard provides information such as:
- Current and maximum sessions.
- Frontend and backend request rates.
- Backend server health.
- Connection errors.
- Response errors.
- Queue lengths.
- Bytes transferred.
- Backend availability changes.
- Configured server weights.
Common server states include:
| State | Meaning |
|---|---|
| UP | The server is considered available |
| DOWN | The server is considered unavailable |
| MAINT | The server is in administrative maintenance mode |
| DRAIN | The server is being removed from ordinary new traffic selection |
| OPEN | A frontend is accepting connections |
Displayed states and their formatting can vary depending on HAProxy version and configuration.
47. Use the HAProxy Runtime API
The HAProxy runtime socket allows authorized administrators to inspect and modify selected runtime settings without editing the configuration file immediately.
The main configuration includes:
stats socket /run/haproxy/admin.sock mode 660 level admin
Install socat:
sudo apt install -y socat
Display runtime information:
echo "show info" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock
Display backend statistics:
echo "show stat" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock
Display available runtime commands:
echo "help" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock
The administrative runtime socket provides powerful control over the load balancer.
Restrict access to authorized administrators and never expose an unrestricted administrative runtime interface publicly.
48. Place a Backend Server into Maintenance Mode
Before performing maintenance on a backend server, you can remove it from ordinary traffic distribution.
For example, disable web01:
echo "disable server web_servers/web01" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock
Verify its status:
echo "show stat" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock |
grep '^web_servers,web01,'
New ordinary traffic should no longer be assigned to web01 while it remains administratively disabled.
Existing connections may continue until they finish or are otherwise terminated.
Do not immediately reboot the backend without checking active sessions and application-specific maintenance requirements.
49. Drain a Backend Before Maintenance
Drain mode can help remove a server from normal new load balancing decisions while allowing existing work to finish.
echo "set server web_servers/web01 state drain" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock
Monitor backend sessions:
echo "show stat" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock |
grep '^web_servers,web01,'
Drain mode can still permit traffic associated with persistence rules, depending on the configuration.
Once the application is ready for maintenance, place the server into maintenance mode:
echo "set server web_servers/web01 state maint" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock
Verify that no remaining application workload will be interrupted before stopping services or rebooting the backend.
50. Return a Backend Server to Service
After maintenance, verify the backend application directly:
curl -i http://10.10.10.11/healthz
Return web01 to normal operation:
echo "set server web_servers/web01 state ready" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock
Verify its status:
echo "show stat" |
sudo socat - UNIX-CONNECT:/run/haproxy/admin.sock |
grep '^web_servers,web01,'
HAProxy will use the server according to its administrative and health check state.
Runtime changes are not necessarily preserved across configuration reloads or service restarts.
For persistent maintenance requirements, update the configuration or implement appropriate server-state persistence.
51. Configure Gradual Backend Recovery
A server returning from maintenance or failure may initially have cold application caches or other initialization overhead.
HAProxy supports a slowstart parameter that gradually restores the effective server weight under supported dynamic balancing behavior.
Example:
server web01 10.10.10.11:80 check slowstart 30s
server web02 10.10.10.12:80 check slowstart 30s
When a server returns to service, HAProxy can gradually increase the traffic assigned to it.
This may help prevent a recently recovered backend from receiving its full workload immediately.
Application readiness checks remain essential. Slowstart does not make an application ready before its required dependencies are available.
52. Add a New Backend Server
One advantage of load balancing is the ability to expand application capacity by adding backend servers.
Prepare the new VPS with the same application version, configuration, and required data access.
Verify connectivity:
curl -i http://10.10.10.13/healthz
Add the server to the existing backend:
server web03 10.10.10.13:80 check slowstart 30s
Validate the configuration:
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
Reload HAProxy:
sudo systemctl reload haproxy
Verify the new server through the statistics dashboard or runtime API.
Monitor its health, response times, error rates, and resource utilization after it begins receiving traffic.
53. Reload HAProxy Without Unnecessarily Interrupting Traffic
Modern HAProxy deployments using the appropriate systemd service and master-worker process model support graceful configuration reloads.
Inspect the installed service definition:
sudo systemctl cat haproxy
Check whether the service defines an appropriate ExecReload operation.
Before each configuration change, create a timestamped backup:
sudo cp -a /etc/haproxy/haproxy.cfg \
"/etc/haproxy/haproxy.cfg.bak.$(date +%Y%m%d-%H%M%S)"
Validate and reload:
sudo haproxy -c -f /etc/haproxy/haproxy.cfg && \
sudo systemctl reload haproxy
Verify the service:
sudo systemctl is-active haproxy
sudo journalctl -u haproxy -n 30 --no-pager
Graceful reloads are generally preferable to complete restarts for ordinary configuration changes.
However, uninterrupted operation depends on the installed service configuration, listener handover behavior, connection types, and the nature of the configuration change.
Long-lived connections may remain associated with older worker processes until they close.
Test reload behavior under representative application traffic before assuming that every change will be completely interruption-free.
54. Configure HAProxy Logging
The example HAProxy configuration sends logs to the local syslog socket:
log /dev/log local0
log /dev/log local1 notice
Check whether rsyslog is installed:
systemctl status rsyslog --no-pager
If required, install and enable it:
sudo apt install -y rsyslog
sudo systemctl enable --now rsyslog
Inspect existing HAProxy logging rules:
sudo grep -Rni haproxy \
/etc/rsyslog.conf /etc/rsyslog.d/
Ubuntu packages may already provide a suitable HAProxy logging configuration.
If no equivalent rule exists, create:
sudo nano /etc/rsyslog.d/49-haproxy-local.conf
Add:
if ($programname == "haproxy") then {
action(type="omfile" file="/var/log/haproxy.log")
stop
}
Validate the rsyslog configuration:
sudo rsyslogd -N1
Restart rsyslog after successful validation:
sudo systemctl restart rsyslog
Generate an application request:
curl -sS -o /dev/null https://example.com/
Inspect the log file:
sudo tail -f /var/log/haproxy.log
If no entries appear, verify the configured syslog socket, HAProxy logging settings, existing rsyslog rules, and service isolation configuration.
Do not create duplicate logging rules unnecessarily.
55. Understand HAProxy HTTP Logs
The option httplog directive enables detailed HTTP transaction logging.
Depending on the configured log format, HAProxy logs may include:
- Client IP address and port.
- Request timestamp.
- Frontend name.
- Backend and selected server.
- Connection and response timing information.
- HTTP response status.
- Bytes transferred.
- Termination state.
- HTTP request method and path.
These logs can help distinguish load balancer problems from backend application problems.
For example, increasing backend response times may indicate application or database saturation rather than a problem with HAProxy itself.
HTTP logs can contain sensitive URLs and application information. Restrict log access and avoid unnecessarily capturing authentication headers, session cookies, or confidential request data.
56. Configure Log Rotation
Inspect existing log rotation configuration:
sudo ls -l /etc/logrotate.d/ | grep haproxy
If a package-provided configuration already covers /var/log/haproxy.log, retain or adapt that configuration.
If no existing rule covers the file, create an appropriate logrotate configuration.
sudo nano /etc/logrotate.d/haproxy-local
Example:
/var/log/haproxy.log {
daily
rotate 14
missingok
notifempty
compress
delaycompress
sharedscripts
postrotate
/usr/bin/systemctl kill -s HUP rsyslog.service
endscript
}
This example retains approximately fourteen daily rotations, subject to actual rotation activity.
Validate without performing rotation:
sudo logrotate -d /etc/logrotate.conf
Resolve any duplicate log definitions before enabling the new rule.
57. Monitor HAProxy Resource Usage
Check service memory and CPU information:
sudo systemctl show haproxy \
-p MemoryCurrent \
-p MemoryPeak \
-p CPUUsageNSec \
-p TasksCurrent
Inspect HAProxy processes:
ps -eo pid,user,%cpu,%mem,rss,args |
grep '[h]aproxy'
Check system memory: