haproxy + keepalived – the free HA load balancer

Load balancers are cool, especially free ones. haproxy and keepalived together can give you a simple HA load balancer at the cost of the hardware you run it on. Here’s how to setup a basic active/passive load balancer with haproxy and keepalived. First the environment:

haproxy-keepalived
Environment:
haproxy-1 public = 10.0.0.10
haproxy-1 private = 192.168.0.10
haproxy-2 public = 10.0.0.11
haproxy-2 private = 192.168.0.11
http-1 private = 192.168.0.12:80
http-2 private = 192.168.0.13:80
http VIP – 10.0.0.12:80

Now the setup:

    1. Install haproxy:

$ sudo apt-get install haproxy

    1. Configure your “proxy” (Server pool) on haproxy-1 and haproxy-2:

Edit /etc/haproxy/haproxy.cfg and add the following:

global
log 127.0.0.1   local0 info
maxconn 4096
user haproxy
group haproxy
daemon

defaults
log     global
mode    http
option  httplog
option  dontlognull
retries 3
option redispatch
maxconn 2000
contimeout      5000
clitimeout      50000
srvtimeout      50000

frontend http-in
bind *:80
default_backend servers

backend servers
mode http
stats enable
stats auth admin:admin
stats uri /haproxy?stats
balance roundrobin
option forwardfor
server http-1 192.168.0.12:80
server http-2 192.168.0.13:80

    1. Enable haproxy – set ENABLED=1 in /etc/default/haproxy
    2. Modify /etc/sysctl.conf to include the following (Be sure and execute $ sudo sysctl –p or reboot):
net.ipv4.ip_nonlocal_bind=1
net.ipv4.ip_forward=1
    1. Finally start the haproxy service:

$ sudo service haproxy start

Your proxy is now setup to forward 10.0.0.12:80 to 192.168.0.12:80 and 192.168.0.13:80

Now let’s create 10.0.0.12 with VRRP using keepalived:

    1. Install keepalived:

$ sudo apt-get install keepalived

    1. Edit /etc/keepalived/keepalived.conf on haproxy-1 and haproxy-2; add the following:
vrrp_script chk_haproxy {
script “killall -0 haproxy”
interval 2
weight 2
}
vrrp_instance VI_1 {
interface eth0
state BACKUP     # MASTER on haproxy-1, BACKUP on haproxy-2
virtual_router_id 51
priority 101     # 101 on master, 100 on backup
virtual_ipaddress {
10.0.0.12
}
track_script {
chk_haproxy
}
}

NOTE: This will monitor the process “haproxy” and if it dies will move the VIP 10.0.0.12 to the BACKUP server.

    1. Start keepalived ($ sudo service keepalived start) and verify your VIP is now available:
$ ip addr show
eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> …
link/ether 00:01:02:03:04:05 brd ff:ff:ff:ff:ff:ff
inet 10.0.0.10/24 brd 10.0.0.255 scope global eth0
inet 10.0.0.12/32 scope global eth0

发表评论