Nginx keepalived

一、架构图

192.168.189.130:keepalived+nginx+tomcat

192.168.189.132:   keepalived+nginx+tomcat

虚拟ip:192.168.189.100

二、tomcat服务

192.168.189.130

192.168.189.132

三、nginx配置

192.168.189.130、192.168.189.132上nginx配置一样

很简单只是做了一个代理,分别代理130、132机器上tomcat服务

server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
        proxy_pass http://192.168.189.130:8080;
            root   html;
        random_index on;
            index  index.html index.htm;
        }

    location /status {
        stub_status;
    }
}

四、keepalived配置

1、master

! Configuration File for keepalived

global_defs {
   router_id LVS_DEVEL
   enable_script_security
}

#在nginx挂掉后触发此脚本来停止keepalived
vrrp_script nginx_status_process {
    script "/root/data/program/nginx/sbin/nginx_status_check.sh"
    user root
    interval 3
}


vrrp_instance VI_1 {
    state MASTER
    #网卡
    interface ens33
    virtual_router_id 51
    priority 100
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    #虚拟ip
    virtual_ipaddress {
        192.168.189.100
    }
    #触发脚本
    track_script {
        nginx_status_process
    }
}

#监听80端口(默认443是https)
virtual_server 192.168.189.100 80 {
    delay_loop 6
    lb_algo rr
    lb_kind NAT
    persistence_timeout 50
    protocol TCP

    #nginx地址
    real_server 192.168.189.130 80 {
        weight 1
        TCP_CHECK {
            connect_timeout 3
            retry 3
            delay_before_retry 3
        }
    }
}

2、backup

! Configuration File for keepalived

global_defs {
   router_id LVS_DEVEL
   enable_script_security
}


#在nginx挂掉后触发此脚本来停止keepalived
vrrp_script nginx_status_process {
    script "/root/data/program/nginx/sbin/nginx_status_check.sh"
    user root
    interval 3
}

vrrp_instance VI_1 {
    state BACKUP
    interface ens33
    virtual_router_id 51
    priority 99
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    virtual_ipaddress {
        192.168.189.100
    }
}

virtual_server 192.168.189.100 80 {
    delay_loop 6
    lb_algo rr
    lb_kind NAT
    persistence_timeout 50
    protocol TCP

    real_server 192.168.189.132 80 {
        weight 1
    TCP_CHECK {
      connect_timeout 3
      retry 3
      delay_before_retry 3
    }
    }
}

3、nginx检测脚本

nginx_status_check.sh

#!bin/sh
#获取nginx进程数
A=`ps -C nginx --no-header |wc -l`

if [ $A -eq 0 ]
    then
        service keepalived stop
fi

4、效果

访问http://192.168.189.100/ 页面显示192.168.189.130服务

killall nginx 后,再次请求,页面显示192.168.189.132服务

在192.168.189.130机器先启动nginx,再启动keepalived,再访问192.168.189.100页面又显示130服务(master权重大) 

原文地址:https://www.cnblogs.com/ph7seven/p/9939220.html