HAProxy Practical Tutorial: Multi-Scenario Deployment and Common Feature Configuration Analysis
This article was last updated 287 days ago. The information within may have evolved or changed; if anything is outdated or broken, please feel free to leave a message in the comments section.
Article Abstract
Addressing the load balancing needs of traditional non-containerized environments, the author compares the limitations of Traefik and chooses HAProxy as the solution, focusing on the implementation details and applicable scenarios of both source code deployment and Docker deployment. The article breaks down the writing logic of the haproxy.cfg configuration file in detail, covering core features such as VIP binding, health checks, SNAT policies, and SSL offloading. Combined with HTTP/TCP/UDP multi-mode adaptation scenarios, it highlights its stability and flexibility advantages in high-concurrency scenarios, providing a reusable practical reference for load balancing deployment in home data centers and enterprise-level applications.
Qwen3-14B · 2026-06-18

Preface

As mentioned at the end of the previous article (see article:Docker Series: Traefik Dynamic File Configuration in Action: Efficient Implementation of Local Network Load Balancing), I was still not quite satisfied with using Traefik to achieve load balancing (hot standby) between the main blog site and the backup blog site in the home data center intranet. After some consideration, I decided to try HAProxy. After all, this is the traditional professional solution for load balancing applications (in non-Docker, non-K8s environments). Traefik was originally designed for microservices and containerized environments, so making it handle traditional load balancing is a bit of a mismatch. Of course, the most important thing is that I can write another article about it~.

Note: Reading this article requires some understanding of traditional load balancing (also known as ”application delivery”), as it requires a lot of basic knowledge in this field; otherwise, reading it might cause some discomfort (side effects like dizziness, sleepiness, etc.~).

Introduction to HAProxy

HAProxy is a high-performance, reliable open-source load balancer and reverse proxy software, widely used in Web services, databases, and other high-concurrency scenarios. It supports L4 (transport layer) and L7 (application layer) traffic distribution, providing rich features including multiple scheduling algorithms, fine-grained health checks, SSL/TLS termination, session persistence, etc. With its outstanding performance, stability, and flexibility, HAProxy has become the preferred load balancing solution for many enterprises and large-scale websites.

Compared to other common free application load balancing software, HAProxy has unique advantages in terms of feature completeness, performance, and configuration:

Software Features Disadvantages compared to HAProxy
Nginx Lightweight, widely used for reverse proxy, supports L4 and L7. Load balancing is not its core feature, performance and flexibility are slightly inferior, and configuration complexity is higher than HAProxy.
LVS Kernel-level load balancing, extremely high performance, suitable for ultra-large-scale traffic scenarios. Only supports L4, lacks application-layer features, complex configuration, and difficult debugging.
Apache Feature-rich, modular design, suitable for existing Apache environments. Performance is far inferior to HAProxy, configuration is complex, and support for high concurrency is poor.
Keepalived Used in conjunction with LVS to achieve high availability, suitable for health checks and failover in simple scenarios. Limited features when used standalone, leans towards health checks and high availability, not a professional load balancer.
Pen/Balance Lightweight load balancer, simple and easy to use, suitable for small-scale environments. Very limited features, only supports basic load balancing needs, not suitable for complex scenarios.

Therefore, from the perspective of traditional professional load balancing software,HAProxy is currently one of the most comprehensive and mature solutions among free load balancing software, performing particularly outstandingly in the following aspects:

Performance and Stability

• High Performance: HAProxy is specifically designed for load balancing and is highly optimized; a single instance can easily support hundreds of thousands or even millions of concurrent connections.

• Stability: Proven by years of practice, HAProxy performs very stably in production environments and is widely used by high-traffic websites and enterprises worldwide.

Comprehensive Features

• Support for Multiple Protocols: Supports TCP and HTTP/HTTPS protocols, covering load balancing needs from L4 (transport layer) to L7 (application layer).

• Diverse Scheduling Algorithms: Supports multiple load balancing algorithms such as round-robin, least connections, source IP hashing, and weights.

• Health Checks: Provides fine-grained backend health checks to ensure only healthy backend servers receive traffic.

• SSL/TLS Termination: Supports terminating and forwarding SSL/TLS traffic, simplifying backend configuration.

• HTTP Layer Features: Supports advanced features such as URL rewriting, request and response modification, and session persistence.

Easy to Extend and Integrate

• High Availability: HAProxy can be used in conjunction with Keepalived to achieve high availability architectures (Active-Passive or Active-Active).

• Dynamic Backend Management: Supports dynamically adding or removing backend servers without restarting the service.

• Logging and Monitoring: Provides detailed logging features and can integrate with monitoring tools like Prometheus and Grafana.

Community and Support

• Strong Community: HAProxy has a very active community and detailed documentation, making it easy to find solutions when encountering problems.

• Enterprise Support: HAProxy provides a commercial version (HAProxy Enterprise), which includes more features (such as advanced health checks, fast patch support, etc.) and professional support services.


Why is HAProxy considered the most comprehensive?

• Broad Feature Coverage: From small applications to enterprise-level deployments, and from simple round-robin to complex session persistence, HAProxy can meet almost all needs.

• Both High Performance and Flexibility: Even in high-concurrency scenarios, HAProxy can still flexibly handle complex rules.

• Adapting to Traditional Application Scenarios: Compared to modern tools like Traefik, HAProxy's configuration method is more traditional and intuitive, making it more suitable for non-containerized environments.

• Ease of Use and Documentation: Although the configuration file may seem slightly complex at first glance, the logic is clear and the documentation is rich, making the learning curve relatively low.


Therefore,HAProxy is the preferred choice for traditional professional load balancing scenarios, especially in applications that require stability, performance, and flexibility.

Note: I originally had high expectations for Traefik, but I was disappointed after trying it out.

Deployment of HAProxy

Choice of Deployment Method

HAProxy has two deployment methods: source installation (using APT as an example) and Docker installation. The comparison of the pros and cons of the two methods is as follows:

Comparison Item Source Deployment Docker Deployment
Advantages
Deployment Complexity Installed via package manager, simple and fast, with no need for additional tool support. No complex dependencies, only requires a Docker environment to start quickly, suitable for cross-platform deployment.
Flexibility Configuration directly modifies system files, convenient to operate, with no container limitations. Can be adjusted by mounting configuration files and environment variables, with strong isolation, adapting to different scenarios.
Performance No container overhead, stable performance, suitable for high-concurrency scenarios. Performance is suitable for most general scenarios, with strong environmental isolation and minimal impact on the host environment.
Updates and Maintenance Use apt upgrade Automatic updates, simplifying the maintenance process. Convenient image updates, simply pull the new version image and restart the container.
Dependency Management The package manager automatically handles dependencies, reducing conflict issues. All dependencies are encapsulated within the image, providing strong isolation without interfering with the host environment.
Portability Deployed using the operating system's native method, suitable for long-term running fixed environments. Images run cross-platform with strong environmental compatibility, suitable for distributed deployment needs.
Resource Consumption No container overhead, high resource utilization, suitable for resource-sensitive scenarios. Containerization technology is well-optimized with efficient resource isolation, imposing almost no extra burden on modern systems.
Debugging Difficulty Debug directly using system tools, offering flexible operation and easy troubleshooting of issues. Container isolation makes it convenient to quickly debug and troubleshoot issues in different environments.
Community Support Official repositories and documentation are stably maintained, suitable for long-term support needs. The Docker community is active with rich resources, supporting rapid resolution of issues.
Disadvantages
Deployment Complexity Requires administrator privileges and depends on the operating system version, which may have support limitations. Requires pre-installing the Docker environment, increasing learning and maintenance costs.
Flexibility Flexibility is limited by the operating system version, making it impossible to freely adjust parameters like source code installation. Dependency versions in the image are fixed, requiring the image to be rebuilt to adjust features or optimize.
Performance Additional system-level optimization may be required to meet specific performance needs. Containers have a small performance overhead; in extreme scenarios, performance is not as good as directly running local services.
Updates and Maintenance Version updates depend on system repositories, which may lag behind the official latest version. Need to regularly pull and verify the reliability of image sources to prevent issues caused by varying image quality.
Dependency Management Restricted by system repository dependency versions, which may lead to incompatibility with some versions. Dependency versions inside the image cannot be changed, resulting in insufficient flexibility.
Portability Depends on the operating system environment, with weak cross-platform capability, unsuitable for heterogeneous environments. Running requires Docker support, which has poor compatibility with traditional environments.
Debugging Difficulty Requires familiarity with debugging tools and log management methods for system services, posing a certain barrier for beginners. Debugging may require entering the container, adding some complexity.
Community Support Fewer community resources, so resolving issues may take more time. Image quality varies, requiring discernment of official and trusted sources.

Both methods have their pros and cons; you can choose based on your needs. I will introduce both deployment methods.


From the perspective of stability,Source Deploymentcompared toDocker Deploymenthas more advantages:

  1. Fewer dependency layers

Source code deployment directly depends on the operating system and compilation environment, reducing compatibility issues caused by changes in the container environment (such as Docker version, base image, etc.).

  1. Higher controllability

Source code deployment allows fine control over versions, compilation parameters, and dependencies, making it suitable for production environments requiring specific optimization, whereas Docker images may use generic configurations, offering lower flexibility.

  1. Stability of updates and maintenance

During source code deployment, updates are subject to manual operations and testing processes, making risks controllable; whereas Docker image updates may introduce additional incompatible or unnecessary components.

  1. Performance and resource optimization

Source code deployment runs directly on the host machine without the extra abstraction layer of containers, potentially offering better performance and resource utilization.

Applicable Scenarios: The source code method is more suitable for core business systems with extremely high requirements for performance and stability.


Source Code Deployment (APT Method)

There are also several ways to deploy HAProxy using the source code method. I will take the simplest APT method as an example:

apt update
apt install haproxy

Ensure that the HAProxy service has started, and then you can check its status using the command:

systemctl status haproxy

If it is normal, it will display as follows:

image.png

For HAProxy installed via the source code method (APT), the path of its haproxy.cfg configuration file is located at:

/etc/haproxy/haproxy.cfg

You can view its content using the following command:

cat /etc/haproxy/haproxy.cfg

The output is as follows:

image.png

Docker Deployment

Deployment via docker run

Create the working directory:

mkdir -p /docker/haproxy

Create the pre-configuration file haproxy.cfg:

vim /docker/haproxy/haproxy.cfg

Then paste the pre-defined configuration file content into it and save it (for the specific format of the configuration file, refer to the ”Configuration File: haproxy.cfg” section at the end of the article).

Optional step: If haproxy is required to perform SSL certificate offloading (decryption), place the SSL certificate and private key files in the specified path on the host machine, assuming it is the ”/etc/ssl/certs” directory.

The command to deploy using docker run is as follows:

docker run --name haproxy -d  -p 80:80 -p 443:443 --restart=always \
-v /docker/haproxy:/usr/local/etc/haproxy \
-v /etc/ssl/certs/certificate.crt:/etc/ssl/certs/mydomain.pem \
-v /etc/ssl/certs/private.key:/etc/ssl/private/mydomain.key \
haproxy:latest

Deployment via docker-compose

If deploying using docker-compose, steps 1, 2, and 3 in the previous section remain unchanged, and starting from step 4, it becomes:

Create the docker-compose.yml file:

vim /docker/haproxy/docker-compose.yml

Then paste the following content into it and save:

version: '3.8'

services:
  haproxy:
    image: haproxy:latest
    container_name: haproxy
    restart: always
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - /docker/haproxy:/usr/local/etc/haproxy
      - /etc/ssl/certs/certificate.crt:/etc/ssl/certs/mydomain.pem
      - /etc/ssl/certs/private.key:/etc/ssl/private/mydomain.key

Start the service:

cd /docker/haproxy
docker-compose up -d

Note: Deploying HAproxy using Docker is indeed not flexible enough, as you need to determine the ports that can provide load balancing services right at the beginning (such as 80 and 443 in the above configuration, because you need to determine-pthe ports on the host machine that need to be mapped to the inside of the container). This method is acceptable for HTTP-type applications (different applications can be distinguished by domain names), but it is very unfriendly for TCP and UDP-type applications. Therefore, if you have not only HTTP-type applications but also TCP and UDP-type applications that require load balancing, it is recommended to deploy using the source code method.

Configuration File: haproxy.cfg

Prerequisites: Review of Basic Load Balancing Concepts

Note: To facilitate understanding the meaning of some options in the HAproxy configuration file, it is necessary to briefly describe several main concepts in load balancing first. Friends who are not interested in technical details can skip this section.

I. VIP (Virtual IP Address)

• Colloquial Explanation: VIP is like a virtual house number; it is the “entry address” presented externally by the load balancing system.

• Role: When you access a website, you are actually accessing this VIP, and the system will distribute your request to a specific server for processing. In this way, even if the backend servers change (such as increasing or decreasing in number), the VIP remains the fixed address for access.

Note: Regarding the concept of VIP, since HAProxy itself cannot directly handle low-level network protocols (such as ARP), it can only respond to IP addresses already bound to its host's network interface. For HAproxy to use a specific virtual IP address (VIP), the VIP must first be manually bound to the network card in the operating system, or managed through tools like Keepalived to ensure the operating system responds to ARP requests. Compared to professional load balancers (such as F5, A10) that have built-in VIP and ARP support, HAProxy relies more on the host's network configuration to perform these functions.

II. Server (IP and Port of the Specific Application)

• Colloquial Explanation: Servers are workers processing specific tasks; they have their own “residential address” (IP) and “post number” (port).

• Role: Each server is responsible for completing user requests, such as loading web pages, processing data, etc. The load balancer will allocate tasks to these servers based on rules.

III. Service Group (A Collection of Multiple Servers)

• Colloquial Explanation: A service group can be understood as a team of workers who complete the same type of task together.

• Role: By organizing servers into a group, the load balancer can allocate work more efficiently. For example, when one of the workers is too busy or takes leave, the task will be assigned to other workers.

IV. Health Check

• Colloquial Explanation: A health check is like giving workers a physical examination to ensure they can work normally.

• Role: The load balancer will periodically check whether the servers are healthy (such as whether the network is smooth and whether the service can respond normally). If a server is found to be "sick," it will temporarily stop assigning tasks to it to avoid affecting the user experience.

V. Session Persistence

• Colloquial Explanation: Session persistence is like equipping workers with specialized toolkits to ensure that the same customer is always served by the same worker.

• Role: In load balancing, session persistence ensures that requests from the same user are always sent to the same server. For example, when you browse products on a shopping website, each request will point to the same server, so the website can remember your previous operations and provide a continuous experience.

VI. Working Mode (TCP, UDP, HTTP)

• Colloquial Explanation: Working modes are like different working environments. TCP, UDP, and HTTP are like three different types of workplaces, each with its own rules and requirements.

• Role: The load balancer handles different types of traffic by choosing different working modes:

• TCP Mode: Handles traditional network communication traffic, such as FTP, telnet, etc.

• UDP Mode: Handles traffic with high real-time requirements, such as video, voice, etc.

• HTTP Mode: Specifically handles web browsing traffic, which is the data requests when users access websites through browsers.

VII. Connection Optimization (Connection Reuse, Limiting Maximum Connections)

• Colloquial Explanation: Connection optimization is like managing worker efficiency. Connection reuse refers to using the same tool multiple times, while limiting maximum connections ensures that workers are not overwhelmed by too much work.

• Role:

• Connection Reuse: By allowing multiple requests to use the same connection, it avoids the overhead of repeatedly establishing connections, thereby improving efficiency.

• Limit Maximum Connections: To prevent a server from overloading, the load balancer sets a maximum number of connections to ensure that the server handles a moderate number of requests and does not work under overload.

VIII. SNAT (Source Network Address Translation)

• Colloquial Explanation: SNAT is like adding a unified “identity tag” to a task, ensuring that each worker's operations are not confused and that feedback on the task can be returned correctly.

• Role: SNAT (Source Network Address Translation) is used to modify the source IP address of data packets. When multiple clients access a server through a load balancer, SNAT can replace the client's source IP address with the load balancer's IP address. In this way, the source of the request received by the server is the load balancer, rather than directly from the client's real IP address.

IX. SSL Offload

• Colloquial Explanation: SSL Offload is like setting up a dedicated decryption station at the entrance of a factory, decrypting and organizing all encrypted information first before sending it to the workshop for processing. This allows the workshop to focus on production without spending time on decryption.

• Role: SSL Offload is used to handle HTTPS encryption and decryption tasks on a load balancer or dedicated device. The client communicates with the load balancer via an encrypted connection (HTTPS). After decrypting it, the load balancer forwards the plaintext data to the backend server (usually using HTTP). This approach reduces the computational burden on backend servers, thereby improving overall performance.


Depending on the load balancing deployment method, the usage of SNAT varies.

SNAT in Inline Deployment Mode

In inline deployment mode, the load balancer is located in the mandatory path of traffic, directly inserted between the client and the server. In this mode, SNAT is optional because the load balancer is already in the traffic path and can perform source address translation by modifying the source IP. However, even without SNAT, the load balancer can still correctly forward traffic to the server and handle responses.

• Example: Suppose the load balancer is located in the middle of the traffic path. The request initiated by the client first reaches the load balancer, which then forwards the request to the backend server. Without SNAT, the server will see the client's real IP address, and the load balancer is only responsible for traffic distribution. However, if SNAT is enabled, the load balancer will change the source IP of the request to its own IP address, so the server sees all requests coming from the load balancer.

SNAT in Bypass (One-Arm) Deployment Mode

In bypass deployment mode, the load balancer is located outside the traffic path, and there is no direct connection between the client and the server. In this case, SNAT is mandatory because it ensures symmetric round-trip paths for traffic. The load balancer must modify the source IP address of the client's request; otherwise, the server will return the response to the client's original IP address instead of the load balancer's IP, leading to request failure or lost responses.

• Example: In a bypass deployment, after the client request reaches the server, the server will directly return the response to the client. Without SNAT, the server will attempt to send the response directly back to the client's real IP address, but since the traffic does not pass through the load balancer, the response will not reach the client correctly. By enabling SNAT, the load balancer replaces the client's source IP with its own IP address, ensuring that the server's response can be correctly returned to the client through the load balancer.

Usage of SNAT in Different Working Modes

• HTTP Mode: In HAProxy's HTTP mode, SNAT is usually not required. This is because in HTTP mode, HAProxy processes traffic based on the HTTP protocol, and each request is forwarded by establishing a new TCP connection. Since these are short-lived connections, each request and response is independent, so the client's source IP is passed directly to the backend server, and HAProxy does not need to modify the source IP. Traffic in this mode is transient, and SNAT is not needed to ensure session correctness.

• TCP/UDP Mode: In TCP and UDP modes, connections are long-lived, and the load balancer is responsible for continuously processing traffic. In this mode, SNAT is required. Since the connection remains open, HAProxy needs to modify the source IP address to ensure that all backend server responses can be returned to the client through the load balancer. Without SNAT, the server might send the response to the client's real IP address, resulting in an asymmetric response path and ultimately failing to return correctly to the client.

Summary

• Inline Deployment Mode: SNAT is optional; the load balancer is directly inserted into the traffic path, and you can choose whether to perform source address translation.

• Bypass Deployment Mode: SNAT is required to ensure that the round-trip path of the connection is symmetric, preventing responses from flowing to the wrong destination.

• HTTP Mode: Since each request is an independent short-lived connection, SNAT is usually not required.

• TCP/UDP Mode: SNAT is required to ensure connection persistence and the correct return path.


Note: I don't want to explain too much about the principles of load balancing in this article, because it cannot be explained clearly in just a few sentences, and it is not the focus of this article. For friends who are interested in the technical principles of load balancing, you can refer to a PPT (converted to PDF) I wrote before. The link is as follows:Introduction to Basic Concepts of Load Balancing. This PPT needs to be presented to achieve the best experience. Just reading it will only give you at most 30% of the experience (and the animation effects are gone after converting to PDF~), but it's still passable to look at. Originally, I wanted to be lazy and just post a link to a good article, but after searching online for a long time, I couldn't find a suitable one, so I had to use my old PPT, delete the irrelevant parts, and use it as a substitute. Since it is a pre-sales document aimed at users, it is not that technical, making it just right for an entry-level introduction.

Explanation of haproxy.cfg Content

No matter which method is used to deploy HAProxy, it will ultimately involve the configuration file ”haproxy.cfg”. However, when deploying using the source code method (APT), this file will be automatically generated with default content (default path:/etc/hparoxy/haproxy.cfg); whereas when deploying using Docker, you need to prepare it in advance (because the -v parameter is required for mounting).

Below is a sample ”haproxy.cfg” content that includes the basic concepts of load balancing mentioned earlier. Suppose the servers corresponding to the HTTP applications that need load balancing are 192.168.1.11:8080, 192.168.1.12:8080, 192.168.1.13:8080, and 192.168.1.14:8080, and domain names are required to distinguish access requests. It needs to configure health checks, session persistence, SNAT using a specified address, as well as connection reuse and server maximum connection limits:

# 全局设置
global
    log stdout format raw local0  # 日志输出到标准输出,便于调试和监控
    maxconn 2000  # 全局最大连接数限制,防止过载
    tune.ssl.default-dh-param 2048  # 设置SSL连接的默认DH参数大小
    daemon  # 后台运行
    stats socket /var/run/haproxy.sock mode 660 level admin  # 管理套接字,用于动态调整配置
    nbthread 4  # 使用4个线程以充分利用多核CPU,提高并发性能

# 默认设置
defaults
    log global  # 继承全局日志设置
    option httplog  # 启用HTTP日志记录
    option dontlognull  # 对空连接请求不记录日志
    timeout connect 5s  # 连接超时设置为5秒
    timeout client 30s  # 客户端超时时间
    timeout server 30s  # 服务器超时时间
    timeout http-request 10s  # HTTP请求超时时间
    timeout http-keep-alive 15s  # 保持长连接超时时间
    maxconn 1000  # 默认最大连接数
    retries 3  # 连接失败时重试3次



# 前端监听配置 - HTTP
frontend http_front
    bind *:80  # 监听80端口
    mode http  # 使用HTTP模式
    option http-server-close  # 每次请求后关闭与客户端的连接
    acl host_app1 hdr(host) -i app1.example.com  # 匹配域名app1.example.com
    acl host_app2 hdr(host) -i app2.example.com  # 匹配域名app2.example.com
    use_backend app1_backend if host_app1  # 如果匹配域名app1.example.com,则转发到app1_backend
    use_backend app2_backend if host_app2  # 如果匹配域名app2.example.com,则转发到app2_backend
    default_backend default_backend  # 如果域名不匹配,转发到默认后端

# 前端监听配置 - HTTPS
frontend https_front
    bind *:443 ssl crt /etc/ssl/private/haproxy.pem  # 监听443端口并启用SSL,使用证书文件haproxy.pem
    mode http  # 使用HTTP模式
    option http-server-close  # 每次请求后关闭与客户端的连接
    acl host_app1 hdr(host) -i app1.example.com  # 匹配域名app1.example.com
    acl host_app2 hdr(host) -i app2.example.com  # 匹配域名app2.example.com
    use_backend app1_backend if host_app1  # 如果匹配域名app1.example.com,则转发到app1_backend
    use_backend app2_backend if host_app2  # 如果匹配域名app2.example.com,则转发到app2_backend
    default_backend default_backend  # 如果域名不匹配,转发到默认后端

# 后端配置 - 应用1
backend app1_backend
    mode http  # 使用HTTP模式
    option httpchk GET /health  # 健康检查路径
    balance roundrobin  # 轮询负载均衡策略
    server app1 192.168.1.11:8080 check  # 后端服务器1
    server app2 192.168.1.12:8080 check  # 后端服务器2
    option redispatch  # 如果会话保持的服务器不可用,则重新分配到其他健康的服务器
    option http-keep-alive  # 后端启用长连接
    default-server maxconn 100
    

# 后端配置 - 应用2
backend app2_backend
    mode http  # 使用HTTP模式
    option httpchk GET /health  # 健康检查路径
    balance roundrobin  # 轮询负载均衡策略
    source 192.168.1.100 # 使用指定的地址作为SNAT的地址,而非默认的HAproxy宿主机IP
    server app3 192.168.1.13:8080 check  # 后端服务器1
    server app4 192.168.1.14:8080 check  # 后端服务器2

# 默认后端配置
backend default_backend
    mode http  # 使用HTTP模式
    balance roundrobin  # 轮询负载均衡策略
    server default1 192.168.1.15:8080 check  # 默认后端服务器

# 统计页面配置
listen stats
    bind *:8085  # 监听端口8085
    mode http  # 使用HTTP模式
    stats enable  # 启用统计页面
    stats uri /stats  # 统计页面路径
    stats realm Haproxy\ Statistics  # 设置统计页面标题
    stats auth admin:password  # 设置访问统计页面的用户名和密码
    stats admin if TRUE  # 允许管理员权限

Interpreting the above configuration from the perspective of the nine basic concepts of load balancing mentioned earlier:

Configuration Content Analysis:

  1. VIP (Virtual IP Address)

Configuration Representation:

bind * :80 
bind * :443 ssl crt /etc/ssl/certs/haproxy.pem。

Explanationbind * :443 ssl crt /etc/ssl/certs/haproxy.pem.

  1. : VIP is represented in the configuration as a combination of the listening IP and port. HAProxy responds to all IP addresses bound to the host by default (such as *), but if a specific VIP is required, that IP must be bound in the operating system in advance, or implemented through tools (such as Keepalived).

Configuration Representation:

server app1 192.168.1.11:8080 check  
server app2 192.168.1.12:8080 check  

Explanationserver app1 192.168.1.11:8080 check

  1. server app2 192.168.1.12:8080 check

Configuration Representation:

backend app_backend
    server app1 192.168.1.11:8080 check
    server app2 192.168.1.12:8080 check

ExplanationService Group (a collection of multiple servers)

  1. Health Checks

Configuration Representation:

option httpchk GET /health

Explanation: Configured to check server health status via the HTTP /health path. If the backend server returns a non-2xx or 3xx response code, the server is considered unavailable.

  1. Session persistence

HAProxy is not configured with session persistence by default. If you want to configure it, the HTTP mode is slightly different from the TCP and UDP modes: TCP and UDP generally use session persistence based on the source IP address, while HTTP mode, in addition to using session persistence based on the source IP address, can also use cookie-based session persistence.

Configuration Representation:

HTTP mode cookie-based session persistence

cookie SERVERID insert indirect nocache

Explanation: Inserts a cookie for each client to mark its associated server. This ensures that subsequent requests from the client are directed to the same server, thereby maintaining session continuity.

TCP or UDP mode session persistence based on source IP address

    # 创建 stick-table 用于源地址粘性会话保持
    stick-table type ip size 200k expire 30m store conn_cur,conn_rate
    # 基于源地址进行会话保持
    stick on src  # 使用客户端源 IP 地址进行会话保持

Explanation: Session persistence based on source address binds a client to a specific backend server by recording the client's IP address. In this way, every time the same client sends a request, the load balancer will always forward its request to the same server based on the record. This method does not rely on client support for cookies, making it suitable for scenarios where the protocol does not support cookies or where session management needs to be simplified.

  1. Working mode (TCP, UDP, HTTP)

Configuration Representation:

frontend http_front 中的 mode http

backend tcp_backend 中的 mode tcp

Explanation: Configured to use HTTP mode to handle Web traffic and TCP mode to handle traffic for other applications (such as databases). Different modes adapt to different protocol requirements.

  1. Connection optimization (connection reuse, limiting maximum connections)

Configuration Representation:

option http-keep-alive

default-server maxconn 100

Explanation: Sets up HTTP connection reuse to reduce the overhead of establishing and closing connections; at the same time, it limits the maximum number of connections for a single server to avoid overload.

  1. SNAT (Source Network Address Translation)

Configuration Representation:

source 192.168.1.100

Explanation: Specifies the source IP address used by SNAT via `source` (this address must be a valid IP address on the device where HAProxy is deployed), rather than the default HAProxy listening address. With this configuration, HAProxy will use the specified source IP address for source address translation (SNAT) instead of using the default bound IP address.

IX. SSL Offload

Configuration Representation:

bind *:443 ssl crt /etc/ssl/certs/haproxy.pem  

Explanation: Listens to HTTPS traffic and decrypts it using an SSL certificate (haproxy.pem). The decrypted plaintext traffic is forwarded to the backend servers via HTTP, reducing the computational load on the backend servers.

Note: All SSL offloading only needs to be configured on the frontend, and all backends uniformly use HTTP mode configuration.


Summary:

This configuration file comprehensively covers the key features of HAProxy, including VIP binding, server management, health checks, working mode selection, connection optimization, SNAT configuration, SSL offload, etc.

Note 1: The above configuration file content only includes what I consider to be commonly used for personal use. HAProxy has many other options that I have not listed one by one. If you have other special requirements, please refer to the official documentation:https://docs.haproxy.org/。

Note 2: In order to explain as many of these options as possible in a single demonstration configuration, the configuration looks relatively complex. However, in daily use, if there are not so many requirements, the configuration file will be very simple.

Note 3: The above nine points are just what I consider to be the most commonly used concepts of load balancing. Since load balancing is a technical field in itself (albeit relatively niche), there are too many technical points, and it is mainly used in commercial fields. For individuals, there is no need to understand it too deeply, so this article will not cover much of it. Interested friends can search online by themselves.

Applying Changes to the Configuration File

If you have customized the haproxy.cfg content according to the previous demonstration, you need to reload the HAProxy configuration for the changes to take effect:

systemctl reload haproxy

After that, assuming the host IP of HAProxy is 192.168.1.200, you only need to configure the relevant DNS resolution: resolve both app1.example.com and app2.example.com to 192.168.1.200, and then you can achieve the following load balancing effect:

Accesshttp://app1.example.com和https://app1.example.comWill load balance to 192.168.1.11:8080 and 192.168.1.12:8080

Accesshttp://app2.example.com和https://app2.example.comWill load balance to 192.168.1.13:8080 and 192.168.1.14:8080

Direct accesshttp://192.168.1.200和https://192.168.1.200Will be directly allocated to the default backend server: 192.168.1.15:8080

Command-Line Tools Related to HAProxy

HAProxy provides several commonly used command-line tools. Combined with some system-provided tools, you can view and manage its status, configuration, and runtime information in real time. The following are some common tools and commands related to HAProxy:

haproxy -v – View HAProxy version

• This command is used to view the version information of HAProxy.

haproxy -v

Output example:

HAProxy version 2.3.9-2+deb11u1 2021/12/01
Copyright 2000-2021 HAProxy Technologies

haproxy -c -f /path/to/haproxy.cfg – Check configuration file syntax

• Before starting or reloading HAProxy, you can use this command to check if the configuration file syntax is correct.

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

Output example:

Configuration file /etc/haproxy/haproxy.cfg is valid

haproxy -st – Terminate the HAProxy instance of the specified process

• If you have multiple HAProxy processes running, you can terminate a specified process by PID.

haproxy -st 

This will gracefully terminate the HAProxy instance.

haproxy -D – Run HAProxy in debug mode

• Start HAProxy with -D to run in debug mode and output detailed debugging information.

haproxy -D -f /etc/haproxy/haproxy.cfg

haproxy -p /var/run/haproxy.pid – Display the PID of the running HAProxy

• This command displays the PID file of the current HAProxy instance.

haproxy -p /var/run/haproxy.pid

netstat or ss – View HAProxy's ports and connection status

• Use the netstat or ss command to view the ports HAProxy is listening on and the status of established connections.

netstat -tuln | grep haproxy

Or use ss (a more modern tool):

ss -tuln | grep haproxy

HAProxy Stats Page (View status via web interface)

• If enabled in the HAProxy configuration statistics page(stats), you can access this page through a browser to view the real-time status of HAProxy.

Example configuration:

listen stats
    bind *:8085  # 监听8085端口,请根据实际环境进行修改
    mode http  # HTTP模式
    stats enable  # 启用统计功能
    stats uri /stats  # 统计页面访问路径
    stats realm Haproxy\ Statistics  # 页面标题
    stats auth admin:password  # 访问凭据
    stats admin if TRUE  # 管理员权限

Then you can access http:// in your browser:8085/stats, enter admin and password for authentication, and then you can view the HAProxy Dashboard, as follows:

image.png

socat or nc – View HAProxy status via Unix socket

• HAProxy supports status queries via Unix sockets. After enabling stats socket in the configuration file, you can interact with HAProxy through the command line.

Example configuration:

global
    stats socket /var/run/haproxy.sock mode 600 level admin

Access the socket via socat or nc (netcat):

echo "show stat" | socat unix-connect:/var/run/haproxy.sock stdio

或

echo "show stat" | nc -U /var/run/haproxy.sock

This allows real-time queries of HAProxy's status, such as connection count, request count, server status, etc.

haproxy -q – Query HAProxy status

• If you have enabled stats socket, you can quickly view the current status of HAProxy with this command.

haproxy -q

ps or top – View HAProxy processes

• You can view HAProxy's process status using the ps or top command to understand information such as process count and CPU usage.

ps aux | grep haproxy

Or:

top -p $(pgrep -d',' -f haproxy)

Summary:

• Use haproxy -v to view the version.

• Use haproxy -c -f to check the configuration file.

• Use netstat or ss to view HAProxy's listening ports and connections.

• If stats is enabled, Pagesyou can view the real-time status through a browser.

• View Unix socket status via socat or nc.

• Use ps or top to view HAProxy processes and resource usage.

These commands and tools help monitor and manage HAProxy's running status, connections, and performance.

Afterword

HAProxy can work independently. For those who are familiar with HAProxy configuration files, there is no need to rely on other applications to use it normally, and many commercial environments do just that. However, HAProxy is after all managed by configuration files. Although the configuration file format is very simple, it is still not very friendly for those who are unfamiliar with the CLI interface, so various third-party Web GUI projects have emerged (though many seem to have disappeared now~). Among them, the more famous one is roxy-wi (also called haproxy-wi). However, this is only for the pursuit of graphical configuration and is not mandatory. Everyone must pay attention to this point. I will write an article specifically to introduce roxy-wi later.

View Related Categories · 3 Matches
📌 Content Structure Prompt:
This content is part of the following knowledge map, where you can view the complete content path: Blog Knowledge Map。
📎 Related Articles
Share this article
The blog content is original, please indicate the source when reposting! The RSS address of the blog is:https://blog.tangwudi.com/feed, welcome to subscribe; if needed, you can join theTelegram Groupto discuss questions together.
No Comments

Send Comment Edit Comment


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗ
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
Kaomoji
Emoji
Little Dinosaur
Flower!
Previous
Next
       

👋 Welcome to “Wudi's Personal Blog”

Here, long-term exploration is mainly carried out around the following directions:

🧱 Personal Digital Infrastructure and Blog System Construction
☁️ Cloudflare and Network Architecture Practice
🧠 AI and Knowledge System Exploration
🛡️ Network Security and Access Optimization
🎵 Music and Sound Cognition
👁️ Cognitive Perspectives and Worldviews