使用keepalived搭建高可用叢集
阿新 • • 發佈:2019-03-26
概覽
涉及理論知識點:VRRP協議 https://blog.csdn.net/zhyvodka/article/details/41800399
準備工作
三臺機器恢復快照,抹掉LVS的實驗痕跡
規劃:
wangzb01 web1
wangzb02 Nginx負載均衡1
wangzb03 Nginx負載均衡2,同時也是web2
搭建Nginx負載均衡
在wangzb02和wangzb03上都要做
安裝Nginx
配置yum源
vi /etc/yum.repos.d/nginx.repo
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
安裝
yum install -y nginx
負載均衡配置
vim /etc/nginx/conf.d/bbs_proxy.conf
upstream bbs { ip_hash; server 192.168.153.133:80; server 192.168.153.135:8080; } server { listen 80; server_name bbs.wangzb.cc; location / { proxy_pass http://bbs; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } }
補充:關於upstream配置 https://blog.csdn.net/zwhfyy/article/details/70856035
安裝配置keepalived
在wangzb02和wangzb03上都要做
安裝
yum install -y keepalived
配置
vi /etc/keepalived/keepalived.conf
global_defs { notification_email { [email protected] //定義接收郵件人 } notification_email_from //定義發郵件地址(實際沒有) smtp_server 127.0.0.1 smtp_connect_timeout 30 router_id 001 } vrrp_script chk_nginx { script "/usr/local/sbin/check_ng.sh" //此指令碼為監控nginx服務的 interval 3 } vrrp_instance wangzb { state MASTER interface ens33 //網絡卡 virtual_router_id 001 priority 100 //權重100,此數值要大於backup advert_int 1 authentication { auth_type PASS auth_pass wangzb //定義密碼 } virtual_ipaddress { 192.168.222.100 //定義VIP } track_script { chk_nginx //定義監控指令碼,這裡和上面vrr_script後面的字串保持一致 } }
補充: keepalived中如何配置第三方郵件告警 https://blog.csdn.net/HzSunshine/article/details/62052398
編寫監控Nginx的指令碼
vim /usr/local/sbin/check_ng.sh
#!/bin/bash#時間變數,用於記錄日誌
d=`date --date today +%Y%m%d_%H:%M:%S`
#計算nginx程序數量
n=`ps -C nginx --no-heading|wc -l`
#如果程序為0,則啟動nginx,並且再次檢測nginx程序數量,#如果還為0,說明nginx無法啟動,此時需要關閉keepalived
if [ $n -eq 0 ]
then
systemctl start nginx #啟動命令
n2=`ps -C nginx --no-heading|wc -l`
if [ $n2 -eq "0" ]; then
echo "$d nginx down,keepalived will stop" >> /var/log/check_ng.log
systemctl stop keepalived
fi
fi
修改許可權
chmod 755 /usr/local/sbin/check_ng.sh
啟動keepalived
檢查防火牆, 要保證VRRP協議放行,SElinux要關閉
Centos6新增埠:
iptables -A INPUT -p vrrp -j ACCEPT
setenforce 0
Centos7新增埠
firewalld-cmd --zone=public --add-port=tcp/vrrp --permanent
firewalld-cmd --reload
啟動
systemctl start keepalived
測試
測試點:
手動停止wangzb01上的nginx服務
手動停止wangzb01上的keepalived服務
設定防火牆禁