Installing HAProxy on Ubuntu 20.04 and 22.04: A Practical Guide to High Availability

Installing HAProxy on Ubuntu 20.04 and 22.04: A Practical Guide to High Availability

High availability is no longer optional in modern server infrastructures. Even brief service disruptions caused by hardware failures, network issues, or unexpected traffic spikes can result in lost users, reduced search engine rankings, and operational downtime.

Relying on a single server introduces a clear single point of failure. To mitigate this risk, load balancing is commonly used to distribute incoming traffic across multiple backend servers, improving reliability, performance, and scalability.

HAProxy is one of the most trusted open-source solutions for this purpose. Known for its efficiency, stability, and precise traffic control, HAProxy is widely deployed in both small-scale and enterprise-grade production environments running on High-Performance USA VPS.

This guide provides a practical, step-by-step walkthrough for installing and configuring HAProxy on Ubuntu 20.04. The same instructions apply to Ubuntu 22.04, making this tutorial suitable for both current and long-term production deployments.

 

What Is HAProxy and How Does It Work?

HAProxy (High Availability Proxy) is an open-source load balancer and proxy server designed for high-performance TCP and HTTP workloads. It routes client requests to backend servers based on configurable rules, health checks, and load-balancing algorithms.

Due to its predictable behavior and low resource consumption, HAProxy is widely used in production environments ranging from single VPS setups to large-scale distributed infrastructures.

Key Advantages of HAProxy

  • Fault Tolerance: Automatic detection and isolation of failed backend servers.
  • Performance: Efficient traffic distribution with minimal latency.
  • Control: Advanced routing, access control, and health-check mechanisms.
  • Security: SSL/TLS termination support to offload encryption overhead.

Common Use Cases for HAProxy

HAProxy is commonly used in the following deployment scenarios:

  • Load balancing high-traffic websites
  • Acting as a reverse proxy in front of application servers
  • Distributing API traffic in microservices architectures
  • Serving as an ingress layer for containerized platforms
  • Improving availability for legacy applications

These use cases demonstrate why HAProxy is often a core component of scalable and resilient infrastructure designs.

 

HAProxy vs Other Load Balancing Solutions (Nginx, Apache, and Cloud Load Balancers)

System administrators frequently compare HAProxy with alternatives such as Nginx, Apache, or managed cloud-based load balancers.

HAProxy excels in scenarios where performance, fine-grained control, and transparency are required. Unlike traditional web servers configured as load balancers, HAProxy is purpose-built for traffic distribution and offers advanced balancing logic with minimal overhead.

While managed cloud load balancers provide convenience and automation, HAProxy remains a strong choice for environments that require predictable costs, deep configuration control, and on-premise or VPS-based deployments.

 

Prerequisites

Before installing HAProxy, ensure the following requirements are met:

  • A VPS running Ubuntu 20.04 or Ubuntu 22.04
  • Root or sudo access
  • Basic familiarity with Linux command-line operations
  • At least one backend web server (Apache or Nginx recommended)

 

Step 1: Update the Operating System

Keeping the operating system up to date reduces the risk of security vulnerabilities and package conflicts.

sudo apt update && sudo apt upgrade -y

 

Step 2: How to Install HAProxy on Ubuntu 20.04 and 22.04

HAProxy can be installed using either the default Ubuntu repositories or an official PPA that provides newer versions.

Method 1: Install from Default Ubuntu Repositories

This method is simple and stable, making it suitable for many environments.

sudo apt install haproxy -y

 

Verify the installation:

haproxy -v

 

Method 2: Install the Latest Stable Version via PPA

For environments that require newer features or performance improvements, installing HAProxy via PPA is recommended.

sudo apt install --no-install-recommends software-properties-common

sudo add-apt-repository ppa:vbernat/haproxy-2.8 -y

sudo apt update

sudo apt install haproxy -y

 

Confirm the installed version:

haproxy -v

 

Step 3: Configuring HAProxy

The main HAProxy configuration file is located at:

/etc/haproxy/haproxy.cfg

 

Back Up the Configuration File

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

 

Edit the Configuration File

sudo nano /etc/haproxy/haproxy.cfg

 

Global and Defaults Configuration

Add or modify the following sections to optimize performance:

global

    log /dev/log local0

    log /dev/log local1 notice

    daemon

    maxconn 2048

    user haproxy

    group haproxy

 

defaults

    log global

    mode http

    option httplog

    option dontlognull

    timeout connect 5000

    timeout client 50000

    timeout server 50000

 

These settings define core behaviors such as logging, connection handling, and timeout management.

 

Frontend and Backend Configuration

The following example assumes two backend web servers:

 

frontend http_front

    bind *:80

    default_backend http_back

 

backend http_back

    balance roundrobin

    server web1 10.0.0.1:80 check

    server web2 10.0.0.2:80 check

 

Note: HAProxy will now distribute incoming requests between these backend servers and automatically remove any server that fails a “check” (health check).

Step 4: Validate and Restart HAProxy

Before applying the configuration, validate the file syntax:

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

 

Restart the service and enable it at boot:

 

sudo systemctl restart haproxy

sudo systemctl enable haproxy

 

Step 5: Load Balancing Algorithms

HAProxy supports multiple load-balancing strategies, each suited for different traffic patterns:

  • Roundrobin: Evenly distributes requests across servers (Default).
  • Leastconn: Sends traffic to the server with the fewest active connections (Best for long sessions).
  • Source: Maintains session persistence based on client IP (Good for apps without shared sessions).

Selecting the appropriate algorithm helps optimize performance and resource utilization.

Step 6: Testing the Configuration

Access the HAProxy server IP address in a browser:

http://your-haproxy-ip

Refreshing the page should alternate responses between backend servers.

You can also test using the command line:

while true; do curl http://your-haproxy-ip; sleep 1; done

 

If a backend server becomes unavailable, HAProxy automatically redirects traffic to healthy servers.

Performance Tuning and Best Practices

While HAProxy performs well with default settings, high-traffic VPS environments can benefit from further optimization:

  1. Adjust maxconn: Set this according to your available RAM and CPU resources.
  2. Monitoring: Use the built-in statistics interface (explained below) to watch for bottlenecks.
  3. Keepalives: Ensure your backend servers support keepalive connections to reduce TCP handshake overhead.

Enabling the HAProxy Statistics Dashboard

To visualize your traffic, add this to your frontend configuration:

frontend http_front

    bind *:80

    stats enable

    stats uri /haproxy?stats

    stats refresh 10s

    stats auth admin:your-strong-password

    default_backend http_back

 

Access the dashboard at: http://your-server-ip/haproxy?stats

Optional: SSL/TLS Termination with HAProxy

In production environments, HAProxy is frequently used to terminate SSL/TLS connections at the load balancer level. This approach reduces the computational load on backend servers and simplifies certificate management.

By handling encrypted connections at the edge, HAProxy allows secure client communication while forwarding traffic internally over HTTP or HTTPS. This centralized model improves performance and simplifies security management for large-scale deployments.

 

Enabling and Securing the HAProxy Statistics Dashboard

The statistics dashboard provides real-time insights into server health and traffic distribution.

frontend http_front

    bind *:80

    stats enable

    stats uri /haproxy?stats

    stats refresh 10s

    stats auth admin:your-strong-password

    default_backend http_back


Replace your-strong-password with a strong, unique password.
Access to the statistics interface should always be restricted to trusted networks or protected using firewall rules.

Access the dashboard at:

http://your-server-ip/haproxy?stats

 

Security Considerations When Using HAProxy

When properly configured, HAProxy contributes to a stronger security posture for your infrastructure. Treating HAProxy as part of the security perimeter helps reduce the overall attack surface.

Important considerations include:

  • Restricting Access: Always restrict access to the statistics interface (Stats Page) using strong authentication and IP whitelisting.
  • Non-Root User: Ensure HAProxy runs as a non-root user (which is the default in most package installations) to limit potential damage in case of a compromise.
  • Limiting Exposure: Only expose necessary ports (e.g., 80 and 443) to the public internet. Use firewalls (UFW) to block everything else.
  • SSL/TLS Termination: Centralize SSL termination at the HAProxy level. This allows you to manage certificates in one place rather than on every backend server.
  • Regular Updates: Keep HAProxy updated to patch known vulnerabilities immediately.

 

Maintaining and Updating HAProxy

Long-term reliability depends on regular maintenance. HAProxy should be managed as a critical infrastructure component, not a “set it and forget it” tool.

Typical maintenance tasks include:

  • Log Monitoring: Regularly review logs (/var/log/haproxy.log) to spot anomalies or attack patterns.
  • Package Updates: Apply updates through the package manager (apt update) to receive security patches.
  • Testing Changes: Always test configuration changes (haproxy -c) before restarting the service to prevent accidental downtime.
  • Staging Environments: Use a staging VPS for major upgrades (e.g., moving from HAProxy 2.6 to 2.8) before applying them to production.

Conclusion

Installing HAProxy on Ubuntu provides a reliable and scalable load-balancing layer that improves availability, performance, and fault tolerance. By intelligently distributing traffic and continuously monitoring backend health, HAProxy helps ensure uninterrupted service delivery even when individual servers fail.

However, software is only half the equation. For true high availability, you need reliable infrastructure.

Need a reliable platform for your load balancer?

At Buyserver.org, we provide high-performance, stable VPS solutions perfect for hosting HAProxy and your critical applications. Experience low latency and 99.9% uptime with our premium servers.

View VPS Plans & Pricing →

 

FAQs

Is HAProxy suitable for production environments?

Yes. HAProxy is widely used in production and is capable of handling very high traffic volumes with minimal overhead.

Does HAProxy support SSL/TLS termination?

Yes. HAProxy fully supports SSL/TLS termination and is commonly used for this purpose.

Can HAProxy be used with a single backend server?

Yes. This setup is often used for monitoring, testing, or preparing for future scaling.