环境准备
Centos7系统,后端服务器提供web服务。
地址规划:
- VS1: 172.18.51.7
- VS2:172.17.51.77
- RS1:172.18.51.74
- RS2:172.18.51.75
- VirtualIP:172.18.51.82
拓扑图:
原理:nginx是高度模块化的应用程序,其中nginx_proxy模块即可实现负载均衡,将前端的用户请求通过调度算法分摊在后端的真实主机,达到均衡的效果。这里使用upstream模块将前端请求转发至后端;利用keepalived配置主备服务器,对各RS的健康状态进行检测,通过共用的虚拟IP地址对外提供服务。
RS:
提供httpd服务,定义web主页,并启动服务
RS的预配置脚本:
vim setparam.sh #!/bin/bash # vip=172.18.51.100 mask='255.255.255.255' case $1 in start) echo 1 > /proc/sys/net/ipv4/conf/all/arp_ignore echo 1 > /proc/sys/net/ipv4/conf/lo/arp_ignore echo 2 > /proc/sys/net/ipv4/conf/all/arp_announce echo 2 > /proc/sys/net/ipv4/conf/lo/arp_announce ifconfig lo:0 $vip netmask $mask broadcast $vip up route add -host $vip dev lo:0 ;; stop) ifconfig lo:0 down echo 0 > /proc/sys/net/ipv4/conf/all/arp_ignore echo 0 > /proc/sys/net/ipv4/conf/lo/arp_ignore echo 0 > /proc/sys/net/ipv4/conf/all/arp_announce echo 0 > /proc/sys/net/ipv4/conf/lo/arp_announce ;; *) echo "Usage $(basename $0) start|stop" exit 1 ;; esac
VS:
当所有real server宕掉时,sorry server顶替,定义其主页,启动服务(注意修改服务端口为8080)
开启nginx的upstream模块,配置反向代理,启动服务(nginx占用80端口)
/etc/nginx/nginx.conf
upstream websers {
server 172.18.51.74:80;
server 172.18.51.75:80;
server 127.0.0.1:8080 backup; #设置其应急响应服务器
/etc/nginx/conf.d/default.conf
location / { root /usr/share/nginx/html; proxy_pass http://websers; #代理至后端主机 index index.html index.htm; }
配置keepalived配置文件:
vs1和vs2的配置文件,主备模式、优先级不一样,其它地方一致;
/etc/keepalived/keepalived.con
! Configuration File for keepalived global_defs { notification_email { root@localhost } notification_email_from keepalived@localhost smtp_server 127.0.0.1 smtp_connect_timeout 30 vrrp_mcast_group4 224.0.101.24 } vrrp_script chk_down { #存在文件时,检测成功,即执行降级;否则不存在,全部退出;实现服务器切换 script "[[ -f /etc/keepalived/down ]] && exit 1 || exit 0" interval 1 weight -5 } vrrp_script ngxstatus { #脚本,健康状态检测,检测nginx是否存活 script "killall -0 nginx && exit 0 || exit 1" interval 1 weight -5 } vrrp_instance sr1 { state MASTER interface ens33 virtual_router_id 51 priority 100 advert_int 1 #nopreempt #非抢占模式(默认抢占模式) authentication { auth_type PASS auth_pass rE+szbuO } track_script { #脚本调用 chk_down ngxstatus } virtual_ipaddress { 172.18.51.82/16 dev ens33 label ens33:0 } notify_master "/etc/keepalived/notify.sh master" notify_backup "/etc/keepalived/notify.sh backup" notify_fault "/etc/keepalived/notify.sh fault" #此处调用脚本实现发邮件给管理员 }
调用脚本
[root@centos703 keepalived]# vim notify.sh #!/bin/bash # contact='root@localhost' notify() { mailsubject="vrrp:$(hostname) to be $1" mailbody="$(hostname) to be $1,vrrp transition, $(date)." echo "$mailbody" | mail -s "$mailsubject" $contact } case $1 in master) notify master ;; backup) notify backup ;; fault) notify fault ;; *) echo "Usage: $(basename $0) {master|backup|fault}" exit 1 ;; esac ~
客户端测试:
模拟服务器正常,一台web服务器宕机,两台都宕机访问情况:
配置vrrp实例后将遵循自动生成VIP地址,主服务器故障时自动实现地址漂移
nginx健康状态检测脚本当nginx宕机时,则会自动将权重减去5,VIP地址漂移至优先级高的主机
原创文章,作者:Mr-Xiao,如若转载,请注明出处:http://www.178linux.com/76023