How to Install and Configure HAProxy Load Balancer on Ubuntu 26.04

By 

•

Published on

•

11 min read

HAProxy on Ubuntu 26.04 routing incoming traffic to two backend servers

When you run a site on two web servers, visitors need a single address they can connect to. HAProxy listens on that address, distributes requests between the servers, and stops sending traffic to a server when it fails its health checks.

This guide explains how to install HAProxy on Ubuntu 26.04, configure an HTTP load balancer with two backends, and verify that both servers receive requests. We will also set up a private stats page and configure HAProxy to serve HTTPS.

Prerequisites

Before you begin, make sure you have the following.

  • An Ubuntu 26.04 server with a user account that has sudo privileges . We use 10.0.0.10 for the load balancer. Port 80 must be available on this server.
  • Two web servers that the HAProxy host can reach over HTTP. We use 10.0.0.11 and 10.0.0.12 on port 80. Both servers should return 200 OK for GET / without requiring a specific hostname.
  • For HTTPS, a domain pointing to the load balancer, an existing certificate and private key for that domain, and port 443 available on the load balancer.

Replace the example IP addresses and domain with your own values throughout.

Installing HAProxy

HAProxy is available in the default Ubuntu repositories. To install it along with curl, run:

Terminal
sudo apt update
sudo apt install haproxy curl

Ubuntu 26.04 ships HAProxy 3.2. To check the installed version, run:

Terminal
haproxy -v

The package starts the HAProxy service after installation. To verify that it is running, type:

Terminal
sudo systemctl status haproxy

Look for active (running) in the output. HAProxy still needs a frontend that listens for web traffic and a backend that lists the servers to receive it.

Configuring HAProxy

The main configuration file is /etc/haproxy/haproxy.cfg. Back up the file before editing it.

Terminal
sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak

Use nano or your preferred text editor to open the configuration file.

Terminal
sudo nano /etc/haproxy/haproxy.cfg

Keep the existing global and defaults sections for logging, timeouts, and TLS defaults. Append the following frontend and backend to the end of the file.

/etc/haproxy/haproxy.cfgconf
frontend http_front
    bind *:80
    default_backend web_backend

backend web_backend
    balance roundrobin
    option httpchk GET /
    server web1 10.0.0.11:80 check
    server web2 10.0.0.12:80 check

The http_front frontend listens on port 80 and sends requests to web_backend. With balance roundrobin, each available server takes a turn. The check keyword enables health checks for a server, and option httpchk GET / tells HAProxy which request to send.

Save the file and check the configuration for errors:

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

When the file is valid, the command prints nothing and returns you to the prompt. Once the configuration passes validation, reload the service.

Terminal
sudo systemctl reload haproxy

A reload lets the old process finish handling existing connections while the new process accepts new ones. Validate the file before reloading after each of the changes below.

If UFW is enabled on the HAProxy host, allow incoming connections on port 80.

Terminal
sudo ufw allow 80/tcp

Testing the Load Balancer

To see which server handled each request, put a small text file in the document root of each backend. The example uses the default Nginx document root . Create the first file on 10.0.0.11.

Terminal
printf 'web1\n' | sudo tee /var/www/html/haproxy-test.txt

Give the file on 10.0.0.12 a different response so you can tell the servers apart.

Terminal
printf 'web2\n' | sudo tee /var/www/html/haproxy-test.txt

From the HAProxy host or another machine that can reach it, send six requests to the load balancer IP.

Terminal
for i in {1..6}; do
    curl -fsS http://10.0.0.10/haproxy-test.txt || break
done

With both backends healthy and no other traffic, you should see alternating responses.

output
web1
web2
web1
web2
web1
web2

If you can safely stop the web service on one of the test servers, wait for HAProxy to mark it down and run the loop again. Every response should come from the remaining server. Start the stopped service again after the test.

Choosing a Balancing Algorithm

roundrobin is a good starting point when both servers have similar capacity. The balance directive also accepts algorithms suited to other traffic patterns.

  • leastconn - Prefer the server with the fewest connections. This works well for long-lived connections such as WebSockets.
  • source - Choose a server based on a hash of the client IP. Requests from the same IP generally go to the same server while the available backends and weights stay the same.

To switch to least-connections, replace balance roundrobin in the existing web_backend section.

conf
    balance leastconn

Validate the file and reload HAProxy for the change to take effect.

Configuring Health Checks

The GET / check accepts HTTP responses in the 2xx and 3xx ranges. That tells you the server can answer an HTTP request, but a redirect or a working home page may tell you little about whether the application is ready.

If your application exposes a /healthz endpoint that returns 200 OK only when it is ready, use the following web_backend block in place of the original. Keep the balancing algorithm you chose for your setup.

conf
backend web_backend
    balance roundrobin
    option httpchk GET /healthz
    http-check expect status 200
    default-server inter 2s fall 3 rise 2
    server web1 10.0.0.11:80 check
    server web2 10.0.0.12:80 check

The http-check expect line requires a 200 response. The default-server line sets the same check interval and thresholds for both servers.

  • inter 2s - Run a check every two seconds.
  • fall 3 - Mark a server down after three consecutive failures.
  • rise 2 - Mark a server up again after two consecutive successes.

Enabling the Stats Page

The built-in stats page shows how many sessions each server is handling, how many requests are queued, and which servers are up. Add a listen block at the end of haproxy.cfg. Binding it to 127.0.0.1 keeps the page off the network. You can reach it only from the HAProxy host itself.

conf
listen stats
    bind 127.0.0.1:8404
    stats enable
    stats uri /stats
    stats refresh 10s
    stats auth admin:replace-this-password

Replace the placeholder with a unique password before you reload. The stats auth line stores the password in plain text, so keep the live configuration out of version control or commit a template with the placeholder.

After validating and reloading HAProxy, open an SSH tunnel from your computer. Use your SSH username in place of your-user.

Terminal
ssh -N -L 127.0.0.1:8404:127.0.0.1:8404 your-user@10.0.0.10

Leave the SSH session open, then visit http://127.0.0.1:8404/stats in your browser and sign in. The tunnel encrypts traffic between your computer and the HAProxy host.

Enabling HTTPS

HAProxy can handle HTTPS connections from clients and forward requests over HTTP to the backends on the private network. This example assumes Certbot has already issued a certificate for load-balancer.example.com. If you use Certbot’s standalone HTTP challenge, renewal needs exclusive access to port 80. Use a renewal method that works while HAProxy is listening, such as a DNS challenge.

Save the following script as /usr/local/sbin/haproxy-cert-deploy. Set domain to the certificate name shown by sudo certbot certificates. The script combines the certificate chain and key in a temporary file that only root can read, then moves the completed PEM into place.

/usr/local/sbin/haproxy-cert-deploysh
#!/bin/sh
set -eu

domain=load-balancer.example.com
lineage="/etc/letsencrypt/live/$domain"
cert_dir=/etc/haproxy/certs

[ "${RENEWED_LINEAGE:-$lineage}" = "$lineage" ] || exit 0

install -d -m 0700 "$cert_dir"
pem=$(mktemp "$cert_dir/.$domain.XXXXXX")
trap 'rm -f "$pem"' EXIT
cat "$lineage/fullchain.pem" "$lineage/privkey.pem" > "$pem"
mv "$pem" "$cert_dir/$domain.pem"

if [ -n "${RENEWED_LINEAGE:-}" ]; then
    /usr/sbin/haproxy -c -f /etc/haproxy/haproxy.cfg
    systemctl reload haproxy
fi

Make the script executable and run it before changing the frontend. This creates the PEM file HAProxy will load.

Terminal
sudo chmod 755 /usr/local/sbin/haproxy-cert-deploy
sudo /usr/local/sbin/haproxy-cert-deploy

Use the following http_front section in place of the original. The crt path must match the PEM file created by the script.

conf
frontend http_front
    bind *:80
    bind *:443 ssl crt /etc/haproxy/certs/load-balancer.example.com.pem
    http-request redirect scheme https unless { ssl_fc }
    default_backend web_backend

The ssl crt option enables TLS and points HAProxy to the PEM file. The redirect applies when ssl_fc is false, which means the client connected over plain HTTP.

Reload HAProxy once the new configuration passes validation.

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

If UFW is enabled, allow incoming HTTPS connections on port 443.

Terminal
sudo ufw allow 443/tcp

Use your domain in both commands to check the HTTP redirect and confirm that the HTTPS request reaches the site with a valid certificate.

Terminal
curl -I http://load-balancer.example.com/
curl -fsS -o /dev/null -w '%{http_code}\n' https://load-balancer.example.com/

The first request should return a 302 with an https:// location. The second should print 200 for the example site.

Register the script as a Certbot deploy hook so HAProxy picks up a new certificate after successful renewal. Use the same certificate name you used in the script when you run the renewal test.

Terminal
sudo install -d /etc/letsencrypt/renewal-hooks/deploy
sudo ln -s /usr/local/sbin/haproxy-cert-deploy /etc/letsencrypt/renewal-hooks/deploy/haproxy
sudo certbot renew --cert-name load-balancer.example.com --dry-run --run-deploy-hooks

During the dry run, the hook uses the existing certificate. On a successful live renewal, Certbot passes the renewed certificate directory in RENEWED_LINEAGE. The script rebuilds the PEM, validates the configuration, and reloads HAProxy.

Passing the Client IP to the Backends

Every request reaches the backends from the load balancer. Their access logs show 10.0.0.10 as the client address, not the IP of your visitor. Your application also cannot tell that the original request used HTTPS.

To pass both details to the backends, add two lines to the http_front section. The complete section looks like this:

conf
frontend http_front
    bind *:80
    bind *:443 ssl crt /etc/haproxy/certs/load-balancer.example.com.pem
    http-request redirect scheme https unless { ssl_fc }
    option forwardfor
    http-request set-header X-Forwarded-Proto https if { ssl_fc }
    default_backend web_backend

The option forwardfor line adds an X-Forwarded-For header with the client IP address. The set-header line sets X-Forwarded-Proto to https and replaces any value the client sent. An application that forces HTTPS reads this header to know the visitor is already on a secure connection.

Validate the file and reload HAProxy for the change to take effect.

The web servers keep logging the load balancer address until you tell them to trust the header. On each Nginx backend, create the following file:

/etc/nginx/conf.d/haproxy-realip.confnginx
set_real_ip_from 10.0.0.10;
real_ip_header X-Forwarded-For;

The set_real_ip_from line accepts the header only on requests that come from the load balancer. Nginx then takes the client address from the last entry in X-Forwarded-For. HAProxy adds that entry. A visitor who sends a fake X-Forwarded-For header cannot change the address you see in the logs.

To test the configuration and reload Nginx, run:

Terminal
sudo nginx -t && sudo systemctl reload nginx

New entries in /var/log/nginx/access.log now show the IP address of the visitor. Health check requests still log 10.0.0.10. HAProxy does not add the header to them.

Viewing HAProxy Logs

Follow the systemd journal for service diagnostics such as startup or reload errors.

Terminal
sudo journalctl -u haproxy -f

If rsyslog is running with Ubuntu’s packaged HAProxy rule, you can follow HTTP requests in /var/log/haproxy.log.

Terminal
sudo tail -f /var/log/haproxy.log

The HTTP log entries show the frontend, backend, and server that handled the request, along with timing information and the response status.

Troubleshooting

HAProxy fails to start or reload
Run sudo haproxy -c -f /etc/haproxy/haproxy.cfg and fix any errors it reports. If validation passes, check sudo journalctl -u haproxy -n 30 for problems such as another service holding port 80 or 443. On Ubuntu, systemctl reload haproxy runs the same check first. If the check fails, the reload stops and your previous configuration keeps running. If you restore the backup, validate it and reload the service, or start it if it is stopped.

The frontend returns 503 and all backends are down
From the HAProxy host, use curl -v http://10.0.0.11/ to check the backend directly. Use /healthz if you configured the stricter check. The basic check accepts 2xx and 3xx responses, while the stricter check requires 200. If the connection fails, check the backend listener and firewall rules.

A backend works in the browser but fails its health check
The basic check sends HTTP/1.0 without a Host header. For a named virtual host, replace the existing option httpchk line with the following two directives. Set the Host header to the hostname the backend expects.

conf
    option httpchk
    http-check send meth GET uri / ver HTTP/1.1 hdr Host load-balancer.example.com

Use uri /healthz if that is the endpoint you want to check.

Requests reach only one backend
Check that both servers are up on the stats page. If you are using balance source, testing from a single IP will usually select the same backend. Switch to roundrobin to verify that both servers can receive requests.

Conclusion

HAProxy is now distributing HTTP and HTTPS traffic across two web servers on Ubuntu 26.04. When you add another web server, give it a server line with check in the backend, then validate the configuration and reload HAProxy. To compare other ways of spreading traffic, see the guide on Linux load balancing techniques .

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 1000+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page