目的:
当用户请求访问时,会通过nginx来访问web服务应用,因此我们必须要保证nginx的高可用,要保证nginx的高可用,我们需要通过keepalived来监控nginx,并对外提供1个虚拟的vip当做ip供用户访问,当用户访问时先访问虚拟的ip即keepalive-master,此时keepalive-master会通过脚本程序监控自己本机下的nginx是否启动,如果启动直接访问,如果挂机,keepalive-master会将自身线程杀掉,然后绑定到keepalived-backup备机上,然后备机会接管keepalive-master的工作,继续访问本机上的nginx,以完成用户的本次请求。
一.准备工作
1.准备2台linux虚拟机,分别安装 jdk,tomcat,nginx,ipvs,keepalived,(详见安装)
2.设置
1.虚拟ip为: 192.168.25.125
2.Master主机ip为:192.168.25.128 ,nginx 端口:80 tomcat 端口为: 8080
3backupr主机ip为:192.168.25.129 ,nginx 端口:80 tomcat 端口为: 8080
二.在nginx.conf的配置文件中配置tomcat的负载均衡
进入命令: vim /usr/local/nginx/conf/nginx.conf
1.在128 和129 两个节点了配置如下内容:
upstream cc.com { server 192.168.25.128:8080; server 192.168.25.129:8080; } location / { proxy_pass http://cc.com; }
2.配置 tomcat的配置文件端口
进入命令: vim /usr/local/install/tomcat/conf/server.xml
3.启动 tomcat
进入命令: cd /usr/local/install/tomcat/bin/
启动命令: sh startup.sh
关闭命令:sh shutdown.sh
进入命令: cd /usr/local/install/tomcat/logs/ && ll
查看日志: tail -f catalina.out
4.启动nginx
启动命令: /usr/local/nginx/sbin/nginx
三.Keepalived设置shell脚本
1.创建脚本文件:
进入命令: cd /usr/local/install/keepalived/etc/keepalived
创建文件: vim nginxCheck.sh
NGINX=/usr/local/nginx/sbin/nginx PROT=80 nmap localhost -p $PORT | grep "$PORT/tcp open" #echo $? if [ $? -ne 0 ];then $NGINX -s stop $NGINX sleep 3 nmap localhost -p $PORT | grep "$PORT/tcp open" [ $? -ne 0] && cd /usr/local/install/keepalived/sbin && pkill keepalived echo "over"
注意: 要对这个脚本文件设置权限 chmod 777 nginxCheck.sh
2.在keepalived.conf中添加对脚本的调用
进入命令: cd /usr/local/install/keepalived/etc/keepalived && ll
编辑命令: vim keepalived.conf
1.在vrrp服务器配置前增加:
vrrp_script chk_http_port {
script "/usr/local/install/keepalived/etc/keepalived/ nginxCheck.sh"
interval 2
weight 2
}
2.在vrrp_instance 配置的最后部分添加:
track_script {
chk_http_prot
}
3.启动keepalived
启动命令: /usr/local/install/keepalived/sbin/keepalived
四.测试、访问
1.测试
命令: ip add
2.访问
在地址栏输入: 192.168.25.125