October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Set Up Highly Available HAProxy Servers with Keepalived

A practical, version-conscious guide to running identical HAProxy nodes with Keepalived VRRP so a virtual IP moves automatically when the active load balancer fails.
Length9 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Run two Linux servers with the same HAProxy configuration and let Keepalived move a reserved virtual IP address (VIP) between them. Clients use only the VIP; if the active load balancer or its HAProxy service fails, VRRP elects the standby and assigns it the address. This removes a single load-balancer failure without changing DNS or client connection settings.

The procedure below uses Debian/Ubuntu and RHEL-family package commands, a VIP of 192.168.1.100, interface eth0, and two backend web servers. Replace those values with addresses from your network. HAProxy and Keepalived versions are not pinned here, so validate option names and the configuration-test command on the releases installed on your systems.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the HAProxy–Keepalived design does

HAProxy terminates or forwards client connections and distributes requests to healthy backend servers. Keepalived implements VRRP (Virtual Router Redundancy Protocol) and owns the failover decision. Only one load-balancer node should normally hold the VIP at a time:

  • lb1 is the preferred MASTER and has the higher VRRP priority.
  • lb2 is the BACKUP and waits for advertisements from lb1.
  • 192.168.1.100 is the reserved VIP that clients and DNS records use.
  • Both nodes run HAProxy with an identical configuration and both can reach every backend.

When Keepalived stops receiving advertisements or a tracked health check fails, it lowers the current node’s election priority or places it into a fault state, depending on the script and weight configuration. The standby then adds the VIP to its interface and begins accepting connections. Existing connections can be interrupted; this arrangement protects availability for new connections rather than replicating TCP session state.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Plan addresses, interfaces, and failure boundaries

Choose two servers on the same Layer-2 or otherwise VRRP-capable subnet. The VIP must be reserved and unused before you start. Do not assign it permanently as a normal address on either host. Verify that the interface name is actually eth0; modern distributions often use names such as ens160 or enp1s0.

Item Example Requirement
Preferred node lb1 MASTER, priority 101
Standby node lb2 BACKUP, priority 100
VRRP interface eth0 Same logical network on both nodes
Virtual router ID 51 Identical on both Keepalived files
Virtual IP 192.168.1.100/24 Reserved, free, and identical in both files
Backend example 10.0.0.11:8080 and 10.0.0.12:8080 Reachable from both load balancers

Allow VRRP advertisements (IP protocol 112) between the two nodes. A firewall or security group that blocks this traffic can make both machines believe they are MASTER, producing a split-brain condition in which both claim the VIP.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prerequisites on both load balancers

Enable binding to the VIP before it is local

HAProxy is configured to bind directly to the VIP. On the standby, that address is absent until failover, so Linux must permit a process to bind to a non-local address.

  1. Create a persistent sysctl setting on each node:
printf 'net.ipv4.ip_nonlocal_bind=1n' | sudo tee /etc/sysctl.d/99-haproxy-vip.conf
  1. Apply it and confirm the value:
sudo sysctl --system
sysctl net.ipv4.ip_nonlocal_bind

The output should show net.ipv4.ip_nonlocal_bind = 1. On systems managed with a traditional /etc/sysctl.conf, sudo sysctl -p is the equivalent apply step after editing that file.

Install the packages

Install both services on both machines, using the package manager for the distribution:

Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
# Debian or Ubuntu
sudo apt update
sudo apt install haproxy keepalived

# RHEL, Rocky, or Alma
sudo dnf install haproxy keepalived

Do not start Keepalived with an unreviewed default configuration. First put the same HAProxy configuration on both nodes, then create the role-specific Keepalived files.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Configure HAProxy identically on lb1 and lb2

Place an equivalent configuration in the distribution’s HAProxy configuration file (commonly /etc/haproxy/haproxy.cfg). The important detail for this topology is that the frontend binds to the VIP, not to each node’s ordinary address.

frontend fe_web
    bind 192.168.1.100:80
    default_backend be_web

backend be_web
    balance roundrobin
    option httpchk GET /health
    server web1 10.0.0.11:8080 check
    server web2 10.0.0.12:8080 check

option httpchk GET /health asks each backend for the specified health endpoint; change the path if your application exposes a different one. The check keyword enables backend health checking, and roundrobin distributes eligible requests in turn. Confirm that the backend service actually returns a successful response for the selected path.

Copy the resulting file without changing addresses, ports, timeouts, certificates, ACLs, or backend membership between lb1 and lb2. Configuration drift can make a failover appear successful while silently changing application behavior.

Enable HAProxy on both nodes:

sudo systemctl enable --now haproxy
sudo systemctl is-active haproxy

If HAProxy refuses to start, inspect its service log and run the distribution’s HAProxy configuration check before proceeding. Keepalived cannot make a failed HAProxy process useful.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Configure Keepalived on the preferred node

Edit /etc/keepalived/keepalived.conf on lb1:

global_defs {
    router_id LB_PRIMARY
    enable_script_security
}

vrrp_script chk_haproxy {
    script "/usr/bin/systemctl is-active --quiet haproxy"
    interval 2
    fall 2
    rise 2
}

vrrp_instance VI_1 {
    state MASTER
    interface eth0
    virtual_router_id 51
    priority 101
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass CHANGE_ME
    }
    virtual_ipaddress {
        192.168.1.100/24 dev eth0
    }
    track_script {
        chk_haproxy
    }
}

Replace CHANGE_ME with the same secret on both nodes and replace eth0 if the interface has another name. The script checks whether the HAProxy systemd unit is active every two seconds. With fall 2, two failed checks are required before the failure is acted on; rise 2 requires two successful checks before recovery is considered. The exact transition timing also depends on VRRP advertisements and your Keepalived version.

Configure the standby node

Copy the file to lb2, then change only the node-specific values shown below:

global_defs {
    router_id LB_SECONDARY
    enable_script_security
}

vrrp_script chk_haproxy {
    script "/usr/bin/systemctl is-active --quiet haproxy"
    interval 2
    fall 2
    rise 2
}

vrrp_instance VI_1 {
    state BACKUP
    interface eth0
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass CHANGE_ME
    }
    virtual_ipaddress {
        192.168.1.100/24 dev eth0
    }
    track_script {
        chk_haproxy
    }
}
Setting lb1 lb2
router_id LB_PRIMARY LB_SECONDARY
state MASTER BACKUP
priority 101 100
virtual_router_id 51
auth_pass The same secret
VIP 192.168.1.100/24

virtual_router_id, authentication, interface, advertisement interval, and VIP must match. The higher priority makes lb1 preferred when both nodes are healthy. Keepalived versions differ in available options; do not add settings such as preemption controls or script weights without checking the man page installed on your system.

Validate the files and start Keepalived

Validate the syntax on each host before enabling the service. Many releases accept:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo keepalived --config-test -f /etc/keepalived/keepalived.conf

The configuration-test flag has varied across versions, so confirm the accepted form with keepalived --help or the local man page if this command is rejected. A successful parse does not prove that the interface, VIP, script path, or firewall rules are correct.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Start Keepalived on both nodes:

sudo systemctl enable --now keepalived
sudo systemctl is-active keepalived

Start the preferred node first when possible, then the standby. Review logs immediately if either service enters a fault state:

sudo journalctl -u keepalived -b
sudo journalctl -u haproxy -b

Confirm which node owns the VIP

On lb1, inspect the configured interface:

ip addr show eth0

The output should contain 192.168.1.100/24. Run the same command on lb2; the standby should not show the VIP while lb1 is healthy. From a client on the permitted network, connect to the VIP and verify that HAProxy reaches the expected backend.

Do not test only from the load balancer itself. A local connection can succeed even when upstream routing, ARP/neighbor updates, or a firewall prevents real clients from reaching the address.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Test failover deliberately

Service failure test

  1. Confirm lb1 owns the VIP and that requests through 192.168.1.100 work.
  2. On lb1, stop HAProxy: sudo systemctl stop haproxy.
  3. Watch Keepalived’s log on both hosts: sudo journalctl -u keepalived -f.
  4. After the health-check and election delay, run ip addr show eth0 on lb2. The VIP should appear there and disappear from lb1.
  5. Send a new request through the VIP and verify that lb2 accepts it.
  6. Restart HAProxy on lb1 with sudo systemctl start haproxy and observe whether your chosen priority and preemption behavior return ownership to lb1.

The documented expectation is that the address moves within a few seconds, not instantaneously. Record the observed interval in your own environment; network latency, script thresholds, advertisement timing, and service startup time all affect it.

Node and network failure tests

Also test a complete lb1 shutdown or loss of its network path. A process-only check cannot detect every failure: a hung HAProxy process may still satisfy systemctl is-active. An HTTP-level or socket-level check that exercises the listener can provide stronger assurance, but it must be implemented and secured for your environment and verified against the Keepalived version you run.

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.

Understand priorities, weights, and script behavior

The track_script block selects the health script for a VRRP instance. A script can influence the instance priority through a weight. A negative weight is subtracted when the script fails; a positive weight adds priority on success. The current Keepalived man-page default for a script weight is 0; older guides report a different default, so use the man page shipped with your version rather than assuming a value.

Some documentation also reports that an instance-level weight can override the weight declared with vrrp_script. Treat that behavior as version-sensitive and test it. A failing script with no effective weight may put the instance into FAULT, remove the VIP, and stop advertisements, but this behavior is reported inconsistently in secondary material. Observe your logs and failover test instead of relying on an undocumented assumption.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prevent split brain

Split brain is the most dangerous failure mode: if the two nodes cannot see each other’s VRRP advertisements, each can conclude that it should own the VIP. Clients may then reach different load balancers, and ARP or neighbor-cache updates can make the result appear intermittent.

  • Permit IP protocol 112 between both nodes in every host firewall, security group, and network ACL.
  • Keep the VRRP interface on a network where multicast or the configured VRRP transport is supported.
  • Where multicast is unsuitable, design a unicast-peer arrangement supported by your Keepalived version and test it during a network partition.
  • Use a separate, reliable heartbeat path when the production data path can fail independently.
  • Monitor for simultaneous VIP ownership and alert on duplicate address detection or conflicting ARP observations.

Do not “fix” a split-brain event by manually assigning the VIP to both hosts. Isolate one node, restore communication, inspect logs, and then bring services back in a controlled order.

Operational checks after deployment

  • Keep the HAProxy files synchronized through configuration management, and review changes on both nodes before reloads.
  • Check that the health endpoint used by option httpchk represents application readiness, not merely that a process exists.
  • Ensure certificates, DNS records, backend routes, and listening ports are present on both load balancers.
  • Review journalctl -u keepalived and journalctl -u haproxy after package upgrades or interface renaming.
  • Repeat service-stop, host-shutdown, and network-partition tests after changing priorities, scripts, firewall rules, or kernel settings.
  • Document who may change the VIP, the VRRP authentication secret, and the failover thresholds.

Troubleshooting by symptom

The standby never receives the VIP

  • Confirm lb1 is no longer advertising and that lb2’s Keepalived service is active.
  • Check that both files use the same virtual_router_id, password, interface, and VIP.
  • Verify that protocol 112 is allowed in both directions.
  • Inspect the Keepalived log for a failed script, parse error, or interface-not-found message.

HAProxy will not start on the standby

  • Confirm net.ipv4.ip_nonlocal_bind is 1 on that host.
  • Check that another process is not using port 80.
  • Validate the HAProxy file and confirm that its bind address is the reserved VIP.
  • Compare the standby file byte-for-byte with the known-good configuration on the primary, excluding only deliberate node-independent differences.

Both nodes show the VIP

  • Treat this as split brain, not as a harmless display issue.
  • Check VRRP reachability, VLAN or subnet consistency, and firewall logs.
  • Remove one node from the client network before restarting or reconfiguring Keepalived.
  • After communication is restored, verify a single owner with ip addr and a client request.

The VIP moves but requests fail

  • Test the backend addresses from lb2 directly.
  • Confirm lb2 has the same HAProxy listeners, certificates, ACLs, and routes.
  • Check that the backend health endpoint responds from both nodes.
  • Inspect ARP or neighbor updates and any upstream firewall rule that references the old load-balancer address.

Deployment checklist

  1. Reserve a free VIP on the same supported network as both load balancers.
  2. Install HAProxy and Keepalived on both hosts.
  3. Enable net.ipv4.ip_nonlocal_bind=1 and verify it.
  4. Deploy an identical HAProxy configuration that binds to the VIP.
  5. Create matching Keepalived files, with lb1 at priority 101 and lb2 at priority 100.
  6. Validate syntax using the command supported by the installed Keepalived release.
  7. Allow VRRP protocol 112 between the nodes.
  8. Start both services and confirm the VIP appears only on lb1.
  9. Stop HAProxy on lb1 and verify that lb2 acquires the VIP and serves a new request.
  10. Restore lb1, inspect logs, and document the observed recovery and ownership behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.