keepalived配置

vrrp_script chk_http_port {
    script "/root/check_nginx_pid.sh"
    interval 2                          #(检测脚本执行的间隔)
    weight 2
}
vrrp_instance VI_1 {
    #备用服务器上为 BACKUP
    state MASTER
    #绑定vip的网卡为ens33,你的网卡可能不一样,这里需要改一下
    interface ens33
    virtual_router_id 52
    #备用服务器上为90
    priority 90
    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 1111
    }
    track_script {
    chk_http_port            #(调用检测脚本)
    }
    virtual_ipaddress {
        192.168.198.24
    }
}

nginx反向代理配置:

user  nginx;
worker_processes  2;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    use epoll;
    worker_connections  1024;
}

http {
include       mime.types;
    default_type  application/octet-stream;
       log_format  main  '$remote_addr - $remote_user [$time_local] "$request"     '

                       '$status $body_bytes_sent "$http_referer" '

                       '"$http_user_agent" "$http_x_forwarded_for"';
    access_log    /var/log/nginx/access.log main;
    #sendfile on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;
     gzip  on;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";
     client_header_buffer_size    1k;
    large_client_header_buffers  4 4k;

upstream proxy_test {
   server 192.168.198.144:80 weight=4 max_fails=2 fail_timeout=30s;     #如果你要测试,把这里换成你自己要代理后端的ip
   server 192.168.198.145:80 weight=9 max_fails=2 fail_timeout=30s;
   #ip_hash;                                              #当负载两台以上用ip来hash解决session的问题,一台就别hash了。
 }
server {
        listen       80;
        server_name  www.mysvr1.com;
location / {
        proxy_pass       http://proxy_test;               #这里proxy_test是上面的负载的名称,映射到代理服务器,可以是ip加端口,   或url
        proxy_set_header Host      $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
location ~ \.(html|php|jsp|jspx|dp)?$
    {
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_pass http://proxy_test;    #转向tomcat处理
    }
   }
}

检查nginx的状况而决定keepalived

#!/bin/bash
A=`ps -C nginx --no-header |wc -l`        
if [ $A -eq 0 ];then                            
      /usr/sbin/nginx                #重启nginx
      if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then    #nginx重启失败,则停掉keepalived服务,进行VIP转移
              killall keepalived                    
      fi
fi