說明:Nginx+Keepalived高可用的兩臺實體主機IP與VIP(虛擬IP)必須為同一網段。
1.兩台主機及預計虛擬:10.194.203.155 、10.194.203.167、10.194.203.200(VIP)←虛擬IP
2.兩台主機均需要安裝Nginx、安裝Keepalived (省略安裝過程,自行百度)
3.Nginx配置(主備一致)←兩台Nginx配置相同
upstream zuulpool{
server 10.194.203.155:8080 weight=4 max_fails=2 fail_timeout=30s;
server 10.194.203.167:8080 weight=4 max_fails=2 fail_timeout=30s;
}
server {
listen 80;
server_name localhost;
location / {
add_header backendIP $upstream_addr;
add_header backendCode $upstream_status;
proxy_pass http://zuulpool/;
index index.html;
root html;
}
4.對兩台主機的keepalived進行配置(keepalived.conf)
vrrp_script check_haproxy {
script "/etc/keepalived/nginx_check.sh" # 配置檢查Nginx進程的shell腳本
interval 2
weight -20
}
vrrp_instance VI_1 {
state BACKUP #主為master
interface eth0 #綁定對應主機網卡 自行查看自己的本地網卡名稱
virtual_router_id 51 #主備須相同
priority 100 #主為150
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
check_haproxy
}
virtual_ipaddress {
10.194.203.200 #設置虛擬IP
}
}
5.keepalived調用的檢查shell腳本(check_haproxy.sh)
#!/bin/bash
A=`ps -C nginx --no-header | wc -l`
if [ $A -eq 0 ];then
/usr/local/nginx/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header | wc -l` -eq 0 ];then
killall keepalived
fi
fi
附圖:
> ip a 查看虛擬IP
附:架構原理圖