haproxy & keepalived

detect

1
2
3
# virtual machine will return 'kvm' or 'vmware', physical machine will return 'none'
systemd-detect-virt
# KVM may have not previlege to config vip, so may could not config vip in keepalived

install

1
2
3
sudo apt install haproxy keepalived  # Debian/Ubuntu
# or
sudo yum install haproxy keepalived # RHEL/CentOS/Rocky Linux

assume there are two server e.g. 10.225.10.50 and 10.225.10.51, and each bootstrap web service with 13307 port

and i want export both service by same port 13308 with same ip

if server is physical machine, could use haproxy & keepalived strategy

if server is virtural machine, could use

haproxy

both server all should config and bootstrap haproxy

config

/etc/haproxy/haproxy.cfg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
defaults
mode tcp
log global
option tcplog
option dontlognull
......

frontend ft_executor
bind *:13308
mode tcp
default_backend bk_executor

backend bk_executor
mode tcp
balance roundrobin
server executor1 10.225.10.50:13307 check
server executor2 10.225.10.51:13307 check

bootstrap

1
2
3
sudo setenforce 0
sudo systemctl enable haproxy
sudo systemctl start haproxy

keepalived

both server all should config and bootstrap keepalived

config

/etc/keepalived/keepalived.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
global_defs {
vrrp_skip_check_adv_addr
# ⚠️ Remove or comment out vrrp_strict if it exists
# vrrp_strict
.......
}

vrrp_script chk_haproxy {
script "pidof haproxy"
interval 2
weight -15
fall 3
rise 2
}

vrrp_instance VI_1 {
state MASTER # server1 is MASTER , server2 should be BACKUP
interface eth0 # replace eth0 with your real network interface
virtual_router_id 51
priority 110 # server1 is 110, server2 should be lower
advert_int 1

# Add unicast configuration, ⚠️ server2 would swap ip , src should be 51, peer should be 50
unicast_src_ip 10.225.10.50 # This server's IP
unicast_peer {
10.225.10.51 # Peer server's IP
}

# Add this line to allow traffic to VIP
accept

authentication {
auth_type PASS
auth_pass dingo # custome password
}

# 如果虚拟机无权限配置vip,需要注释掉vip的配置
#virtual_ipaddress {
# 10.225.10.160/24 dev eth0 label eth0:vip
#}

track_script {
chk_haproxy
}
}

config virtual ip as 10.225.10.160

bootstrap

1
2
sudo systemctl enable keepalived
sudo systemctl start keepalived