Skip to content

Commit 21a554c

Browse files
adamoverajddocs
andauthored
[NEW] Getting Started with HAProxy Part One: TCP Load Balancing (#7087)
* Getting Started with HAProxy Part One: TCP Load Balancing * Tech Edit 1 * CI Tests Fix 1 * CI Tests Fix 2 * CI Tests Fix 3 * Tech Edit 2 * Tech Edit 3 * Tech Edit 4 * Tech Edit 5 * Tech Edit 6 * copy edit --------- Co-authored-by: John Dutton <[email protected]>
1 parent d6e8f98 commit 21a554c

File tree

4 files changed

+337
-0
lines changed

4 files changed

+337
-0
lines changed
Loading
Loading
Loading
Lines changed: 337 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,337 @@
1+
---
2+
slug: getting-started-with-haproxy-tcp-load-balancing-and-health-checks
3+
title: "Getting Started with HAProxy TCP Load Balancing and Health Checks"
4+
description: "Learn how to install and configure HAProxy for load balancing and health checks on Ubuntu, CentOS Stream, and openSUSE Leap."
5+
authors: ["Tom Henderson"]
6+
contributors: ["Tom Henderson"]
7+
published: 2024-08-21
8+
keywords: ['haproxy','haproxy load balancing','haproxy setup tutorial','haproxy active health checks','haproxy passive health checks','install haproxy on ubuntu','install haproxy on centos','install haproxy on opensuse','haproxy frontend configuration','haproxy backend configuration','haproxy health check configuration']
9+
license: '[CC BY-ND 4.0](https://creativecommons.org/licenses/by-nd/4.0)'
10+
external_resources:
11+
- '[HAProxy Official Documentation](https://www.haproxy.com/documentation/)'
12+
13+
---
14+
15+
[HAProxy](https://www.haproxy.org/) serves as a reverse proxy between frontend client requests and backend server resources, and can be configured at Layer 4 (network) or Layer 7 (application). A common use of HAProxy is as an intelligent network load balancer. In this role, HAProxy routes incoming frontend traffic to designated backend instances. By default, no load balancing is applied, however, HAProxy can be configured to use various load balancing methods, including:
16+
17+
- **Round Robin**: Distributes incoming connections evenly across all available backend servers by sequentially assigning each new connection to the next server in the pool.
18+
- **Least Connections**: Directs incoming connections to the backend server with the fewest active connections, helping to balance the load more evenly based on current server utilization.
19+
- **Health Checks**: Continuously monitors the health of backend servers. Servers that fail health checks are automatically removed from the pool until they recover, ensuring that only healthy servers receive traffic.
20+
21+
This guide demonstrates how to install HAProxy onto three Linux distributions: Ubuntu, CentOS Stream, and openSUSE Leap. It also uses an example WordPress deployment with sample configurations to implement and test HAProxy's TCP load balancing and health check features.
22+
23+
## Before You Begin
24+
25+
1. To be used as your HAProxy instance, deploy a Compute Instance running one of the `Ubuntu 24.04 LTS`, `CentOS Stream 9`, or `openSUSE Leap 15.6` distributions, and assign the instance to a VLAN. See our [Getting Started with Linode](/docs/products/platform/get-started/) and [Creating a Compute Instance](/docs/products/compute/compute-instances/guides/create/) guides.
26+
27+
HAProxy can be deployed using a [Nanode](https://www.linode.com/pricing/) plan for testing purposes. See HAProxy's [hardware recommendations](https://www.haproxy.com/documentation/haproxy-enterprise/getting-started/installation/linux/#hardware-recommendations) for production-level workloads.
28+
29+
1. Follow our [Setting Up and Securing a Compute Instance](/docs/products/compute/compute-instances/guides/set-up-and-secure/) guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.
30+
31+
1. This guide uses WordPress backend instances to demonstrate how HAProxy controls network traffic flows at both the TCP/Network (Layer 4) and HTTP/Application (Layer 7) levels. Follow the steps in our [Deploy WordPress through the Linode Marketplace](/docs/marketplace-docs/guides/wordpress/) guide to create three backend WordPress test instances. Fill out all required fields under **WordPress Setup**, and use default values along with the following options:
32+
33+
- **The stack you are looking to deploy Wordpress on**: Choose either **LAMP** or **LEMP**.
34+
- **Website title**: For each instance, enter `backend1`, `backend2`, and `backend3`, respectively.
35+
- **Region**: Select the same location the HAProxy instance is in.
36+
- **Linode Plan**: A **Shared CPU**, **Nanode 1 GB** is sufficient to test and demonstrate HAProxy options.
37+
- **Linode Label**: Label each instance to correspond with the website titles `backend1`, `backend2`, and `backend3`, respectively.
38+
- **VLAN**: Attach the instances to the same VLAN as the HAProxy instance.
39+
40+
Each server is generated with an `index.html` home page that indicates the given title of the website hosted on the instance (`backend1`, `backend2`, or `backend3`). Open a web browser and navigate to each server's IP address to verify that the example test servers are functioning. Take note of the IP addresses of each backend instance, as they are used later.
41+
42+
{{< note >}}
43+
This guide is written for a non-root user. Commands that require elevated privileges are prefixed with `sudo`. If you’re not familiar with the `sudo` command, see the [Users and Groups](/docs/guides/linux-users-and-groups/) guide.
44+
{{< /note >}}
45+
46+
## Install HAProxy
47+
48+
To install HAProxy, log into the HAProxy instance as your limited sudo user, and complete the steps below.
49+
50+
1. Select your distribution, and use the command to install HAProxy:
51+
52+
{{< tabs >}}
53+
{{< tab "Ubuntu 24.04 LTS" >}}
54+
Use `apt` to install HAProxy on an Ubuntu 24.04 LTS instance:
55+
56+
```command
57+
sudo apt install haproxy
58+
```
59+
{{< /tab >}}
60+
{{< tab "CentOS Stream 9" >}}
61+
Use `dnf` to install HAProxy on a CentOS Stream 9 instance:
62+
63+
```command
64+
sudo dnf install haproxy
65+
```
66+
{{< /tab >}}
67+
{{< tab "openSUSE Leap 15.6" >}}
68+
Use `zypper` to install HAProxy on a openSUSE Leap 15.6 instance:
69+
70+
```command
71+
sudo zypper in haproxy
72+
```
73+
{{< /tab >}}
74+
{{< /tabs >}}
75+
76+
1. Verify the HAProxy installation by checking the installed version number:
77+
78+
```command
79+
sudo haproxy -v
80+
```
81+
82+
{{< tabs >}}
83+
{{< tab "Ubuntu 24.04 LTS" >}}
84+
```output
85+
HAProxy version 2.8.5-1ubuntu3 2024/04/01 - https://haproxy.org/
86+
Status: long-term supported branch - will stop receiving fixes around Q2 2028.
87+
Known bugs: http://www.haproxy.org/bugs/bugs-2.8.5.html
88+
Running on: Linux 6.8.0-44-generic #44-Ubuntu SMP PREEMPT_DYNAMIC Tue Aug 13 13:35:26 UTC 2024 x86_64
89+
```
90+
{{< /tab >}}
91+
{{< tab "CentOS Stream 9" >}}
92+
```output
93+
HAProxy version 2.4.22-f8e3218 2023/02/14 - https://haproxy.org/
94+
Status: long-term supported branch - will stop receiving fixes around Q2 2026.
95+
Known bugs: http://www.haproxy.org/bugs/bugs-2.4.22.html
96+
Running on: Linux 5.14.0-496.el9.x86_64 #1 SMP PREEMPT_DYNAMIC Mon Aug 12 20:37:54 UTC 2024 x86_64
97+
```
98+
{{< /tab >}}
99+
{{< tab "openSUSE Leap 15.6" >}}
100+
```output
101+
HAProxy version 2.8.6 2024/02/15 - https://haproxy.org/
102+
Status: long-term supported branch - will stop receiving fixes around Q2 2028.
103+
Known bugs: http://www.haproxy.org/bugs/bugs-2.8.6.html
104+
Running on: Linux 6.4.0-150600.23.17-default #1 SMP PREEMPT_DYNAMIC Tue Jul 30 06:37:32 UTC 2024 (9c450d7) x86_64
105+
```
106+
{{< /tab >}}
107+
{{< /tabs >}}
108+
109+
1. Use `systemctl` to start HAProxy:
110+
111+
```command
112+
sudo systemctl start haproxy
113+
```
114+
115+
1. Use `systemctl` to configure HAProxy to automatically start after a reboot:
116+
117+
```command
118+
sudo systemctl enable haproxy
119+
```
120+
121+
1. Verify HAProxy is `active (running)`:
122+
123+
```command
124+
systemctl status haproxy
125+
```
126+
127+
```output
128+
● haproxy.service - HAProxy Load Balancer
129+
Loaded: loaded (/usr/lib/systemd/system/haproxy.service; enabled; preset: enabled)
130+
Active: active (running) since Tue 2024-09-17 20:37:22 UTC; 1 day 1h ago
131+
Docs: man:haproxy(1)
132+
file:/usr/share/doc/haproxy/configuration.txt.gz
133+
Process: 46011 ExecReload=/usr/sbin/haproxy -Ws -f $CONFIG -c -q $EXTRAOPTS (code=exited, status=0/SUCCESS)
134+
Process: 46014 ExecReload=/bin/kill -USR2 $MAINPID (code=exited, status=0/SUCCESS)
135+
Main PID: 35012 (haproxy)
136+
Status: "Ready."
137+
Tasks: 2 (limit: 1068)
138+
Memory: 40.6M (peak: 75.5M swap: 224.0K swap peak: 23.9M)
139+
CPU: 37.675s
140+
CGroup: /system.slice/haproxy.service
141+
├─35012 /usr/sbin/haproxy -Ws -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -S /run/haproxy-master.sock
142+
└─46018 /usr/sbin/haproxy -sf 45988 -x sockpair@5 -Ws -f /etc/haproxy/haproxy.cfg -p /run/haproxy.pid -S /run/haproxy-master.sock
143+
```
144+
145+
## The HAProxy Configuration File
146+
147+
HAProxy is controlled through its configuration file and the CLI. The default HAProxy configuration file is created at `/etc/haproxy/haproxy.cfg` during installation, and contains the settings needed to perform network balancing and flow control. It can be edited with any command line-based text editor.
148+
149+
To edit and use the TCP load balancing and health check functions in this guide, open the HAProxy configuration file with the text editor of your choice:
150+
151+
```command
152+
sudo nano /etc/haproxy/haproxy.cfg
153+
```
154+
155+
## TCP Load Balancing
156+
157+
Load balancing is defined in two sections of the HAProxy configuration file: `frontend` and `backend`. Below are example `frontend` and `backend` configurations for TCP load balancing:
158+
159+
160+
### Frontend Configuration
161+
162+
```file {title="/etc/haproxy/haproxy.cfg"}
163+
frontend web-test
164+
bind *:80
165+
mode tcp
166+
default_backend web-test
167+
```
168+
169+
- `frontend` declares that this section is for a frontend configuration called `web-test`.
170+
- `bind` specifies the interface and port that HAProxy listens to for incoming connections. Here, `*:80` means that HAProxy listens on all available IP addresses (`*`) on port `80`, which is the standard port for web traffic.
171+
- `mode` is set to TCP, so that HAPRoxy handles traffic at the transport layer.
172+
- `default_backend` directs this traffic to a backend named `web-test`, as defined in the next section.
173+
174+
### Backend Configuration
175+
176+
```file {title="/etc/haproxy/haproxy.cfg"}
177+
backend web-test
178+
mode tcp
179+
balance roundrobin
180+
server server1 {{< placeholder "backend1_VLAN_IP_ADDRESS" >}}:80
181+
server server2 {{< placeholder "backend2_VLAN_IP_ADDRESS" >}}:80
182+
server server3 {{< placeholder "backend3_VLAN_IP_ADDRESS" >}}:80
183+
```
184+
185+
- `backend` declares that this section is for a backend configuration called `web-test`.
186+
- `mode` is again set to TCP, telling HAPRoxy to handle traffic at the transport layer.
187+
- `balance` is set to the Round Robin method, which connects each client reaching the HAProxy server's IP address to the next server in the list.
188+
- `server` statements define the backend servers using the VLAN addresses specified during the initial HAProxy setup.
189+
190+
## TCP Health Checks
191+
192+
HAProxy’s load balancing function can also select servers based on their health status. Health checks can be either active or passive. An active health check probes each backend server individually for specific health attributes, whereas a passive check relies on basic connection error information by protocol (Layer 4/TCP or Layer7/HTTP).
193+
194+
To enable a basic server health check, include the `check` keyword in the `server` entry of your HAProxy configuration file:
195+
196+
```file {title="/etc/haproxy/haproxy.cfg"}
197+
server server1 {{< placeholder "backend1_VLAN_IP_ADDRESS" >}}:80 check
198+
```
199+
200+
When the `check` keyword is included, HAProxy sends a SYN/ACK request to determine if a server is active. In some cases, servers may correctly respond to this type of query, while individual services and applications may still be down or unavailable.
201+
202+
### Active TCP Health Checks
203+
204+
Active health checks provide more sophisticated monitoring by sending application-specific queries to backend servers and expecting a valid response in return.
205+
206+
To have HAProxy check server health at specified intervals, include the `inter` keyword along with an interval value. For example:
207+
208+
```file {title="/etc/haproxy/haproxy.cfg"}
209+
server server1 {{< placeholder "backend1_VLAN_IP_ADDRESS" >}}:80 check inter 4
210+
```
211+
212+
In this example, HAProxy checks the first server in the pool every four seconds. If the server does not respond as expected, it is marked as down. This process functions like a ping-style health check to verify server availability.
213+
214+
### Passive TCP Health Checks
215+
216+
HAProxy uses the TCP protocol to perform passive health checks on backend servers. With passive health checks, HAProxy monitors Layer 4 (TCP) traffic for errors and marks a server as down when a specified error limit is reached.
217+
218+
Below is an example of the syntax used for a passive health check:
219+
220+
```file {title="/etc/haproxy/haproxy.cfg"}
221+
server backend1 {{< placeholder "backend1_VLAN_IP_ADDRESS" >}}:80 check observe layer4 error-limit 10 on-error mark-down
222+
```
223+
224+
This configuration specifies a passive health check that observes TCP errors (`observe layer4`). If the number of errors reaches the specified limit of 10 (`error-limit 10`), the server is marked as down (`on-error mark-down`). To optimize performance and reliability, you can adjust the intervals and error limits for different servers based on their capacity, role, or complexity. For more information, refer to the [HAProxy documentation on active health checks](https://www.haproxy.com/documentation/hapee/1-8r1/load-balancing/health-checking/active-health-checks/).
225+
226+
## Configure TCP Load Balancing with Health Checks
227+
228+
Set the HAProxy configuration file to perform TCP load balancing with basic passive health checks.
229+
230+
1. Open the HAProxy configuration file with the text editor of your choice:
231+
232+
```command
233+
sudo nano /etc/haproxy/haproxy.cfg
234+
```
235+
236+
1. Append the following code to the end of the file, and save your changes:
237+
238+
```file {title="/etc/haproxy/haproxy.cfg"}
239+
frontend web-test
240+
bind *:80
241+
mode tcp
242+
default_backend web-test
243+
244+
backend web-test
245+
mode tcp
246+
balance roundrobin
247+
server server1 {{< placeholder "backend1_VLAN_IP_ADDRESS" >}}:80 check
248+
server server2 {{< placeholder "backend2_VLAN_IP_ADDRESS" >}}:80 check
249+
server server3 {{< placeholder "backend3_VLAN_IP_ADDRESS" >}}:80 check
250+
```
251+
252+
1. Restart HAProxy to enable the changes made to the configuration file:
253+
254+
```command
255+
sudo systemctl restart haproxy
256+
```
257+
258+
{{< note title="Check for syntax errors" >}}
259+
If you encounter any errors after reloading HAProxy, run the following command to check for syntax errors in your `haproxy.cfg` file:
260+
261+
```command
262+
sudo haproxy -c -f /etc/haproxy/haproxy.cfg
263+
```
264+
265+
An error message is returned if the configuration file has logical or syntax errors. When the check is complete, each error is listed one per line.
266+
267+
This command only verifies the syntax and basic logic of the configuration, and it does not guarantee that the configuration works as intended when running.
268+
{{< /note >}}
269+
270+
### Test TCP Load Balancing
271+
272+
Load balancing can be verified by visiting the HAProxy instances's public IP address.
273+
274+
{{< note title="CentOS Stream 9" >}}
275+
The default firewall settings for CentOS Stream 9 must be changed prior to testing. Run the following command to temporarily open port `80` to `tcp` traffic:
276+
277+
```command
278+
sudo firewall-cmd --add-port=80/tcp
279+
```
280+
281+
Alternatively, use the commands below to configure the firewall to permanently allow `tcp` traffic on port `80`:
282+
283+
```command
284+
sudo firewall-cmd --permanent --add-port=80/tcp
285+
sudo firewall-cmd --reload
286+
```
287+
{{< /note >}}
288+
289+
1. Open a web browser and navigate to the HAPRoxy instance's public IP address:
290+
291+
```command
292+
http://{{< placeholder "HAProxy_PUBIC_IP_ADDRESS" >}}
293+
```
294+
295+
The WordPress web page for `backend1` should appear:
296+
297+
![The 2024 default WordPress homepage served from backend1.](2024-Default-WordPress-Homepage-backend1.png)
298+
299+
{{< note title="Certificate warnings" >}}
300+
If your browser warns of no HTTPS/TLS certificate, ignore the warning or use the advanced settings to reach the site.
301+
{{< /note >}}
302+
303+
1. Open another browser tab and enter the same HAProxy server IP address. This time, the default page for `backend2` should be displayed:
304+
305+
![The 2024 default WordPress homepage served from backend2.](2024-Default-WordPress-Homepage-backend2.png)
306+
307+
1. Repeat this process in a third browser tab, and the `backend3` server's web page should appear:
308+
309+
![The 2024 default WordPress homepage served from backend3.](2024-Default-WordPress-Homepage-backend3.png)
310+
311+
The HAProxy gateway is now successfully balancing traffic between the three backend instances using the Round Robin method.
312+
313+
### Verify TCP Health Checks
314+
315+
Health checks can be verified by removing one of the backend instances from the server pool. This should trigger a health check failure, causing HAProxy to exclude the unresponsive server from the backend pool.
316+
317+
1. Open the Cloud Manager and choose **Linodes**
318+
319+
1. Click on the ellipsis (**...**) to the right of your first backend instance, `backend1`.
320+
321+
1. Choose **Power Off**, then click **Power Off Linode**.
322+
323+
1. Reload the web browser tabs. HAProxy should no longer route traffic to `backend1`, effectively removing it from the pool.
324+
325+
1. Return to the HAProxy instance and check the logs:
326+
327+
```command
328+
sudo tail -f /var/log/haproxy.log
329+
```
330+
331+
Your output should contain a "WARNING" line regarding the "DOWN" status of `server1`:
332+
333+
```output
334+
[WARNING] (4494) : Server web-test/server1 is DOWN, reason: Layer4 connection problem, info: "No route to host", check duration: 1ms. 2 active and 0 backup servers left. 0 sessions active, 0 requeued, 0 remaining in queue.
335+
```
336+
337+
This shows that HAProxy's TCP health checks are working as intended.

0 commit comments

Comments
 (0)