nginx+keepalived實現高可用負載均衡
阿新 • • 發佈:2022-04-17
一、nginx+keepalived-高可用負載均衡
規劃
keepalived-master 192.168.100.11
keepalived-backup 192.168.100.12
VIP 192.168.100.20
web-nginx 192.168.100.14
配置nginx負載均衡
安裝nginx
master 和 backup都要安裝(後端web伺服器可選擇httpd或者nginx,本例後端web伺服器使用nginx)
yum install -y nginx
修改nginx配置檔案
# master和backup伺服器都要修改 # vim /etc/nginx/conf.d/lb.conf # 增加子配置檔案lb.conf-master和backup保持一致 # 注意主配置檔案和子配置檔案監聽埠不能衝突 upstream pythonwebs { server 10.0.0.14 weight=2 max_fails=2 fail_timeout=2; } server { listen 80; server_name _; access_log /var/log/nginx/access.log main; location / { proxy_pass http://pythonwebs; proxy_redirect default; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_next_upstream error timeout http_500 http_502 http_503 http_504; } }
設定完成,備份的第二臺代理伺服器也同樣的設定; 至此,nginx實現負載均衡功能已經設定完成。訪問兩臺代理伺服器,都會自動跳轉到兩臺後臺真實伺服器上。
配置keepalived
master和backup都要安裝
yum -y install keepalived
備份keepalived配置檔案
keepalived-master配置檔案
# vim /etc/keepalived/keepalived.conf ! Configuration File for keepalived global_defs { router_id keep-master } vrrp_script check_nginx { script "/etc/keepalived/check_nginx.sh" interval 5 } vrrp_instance VI_1 { state MASTER interface ens32 virtual_router_id 51 priority 100 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.100.20 } track_script { check_nginx } }
nginx檢測指令碼
# vim check_nginx.sh # nginx檢測指令碼
#!/bin/bash
#檢查http是否線上
curl -I http://localhost &> /dev/null
if [ $? -ne 0 ]
then
systemctl stop keepalived
# else
fi
keepalived-backup配置檔案
# vim /etc/keepalived/keepalived.conf ! Configuration File for keepalived global_defs { router_id keep-slave } vrrp_script check_nginx { script "/etc/keepalived/check_nginx.sh" interval 5 } vrrp_instance VI_1 { state BACKUP interface ens32 virtual_router_id 51 priority 50 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 192.168.100.20 } track_script { check_nginx } }
nginx檢測指令碼
# vim check_nginx.sh # nginx檢測指令碼
#!/bin/bash
#檢查http是否線上
curl -I http://localhost &> /dev/null
if [ $? -ne 0 ]
then
systemctl stop keepalived
# else
fi
至此keepalived+nginx高可用叢集搭建完畢,瀏覽器訪問vip:192.168.100.20驗證即可