• 环境

  • 网络拓扑图
  • Nginx 配置
  • 安装
  • 配置
    • 主master配置
    • 从Slave配置
  • 启动
  • 添加自启动
  • 故障切换


环境

服务器 IP VIP 软件包 备注
web1 MASTER 192.168.1.101 192.168.1.100 Nginx,keepalived  
web2 BACKUP 192.168.1.102 192.168.1.100 Nginx,keepalived  

 

网络拓扑图


Nginx 配置

#cat vhost.conf

#配置后端地址池

upstream web {
    ip_hash;        #将同一IP用户转发到后端同一台服务器,解决session丢失问题
    server 192.168.1.101;
    server 192.168.1.102;
}
 
server
{
    listen 80;
    server_name www.test.com;
    location / {
        proxy_pass http://web;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
access_log /opt/nginx/logs/web.log main;
}

注:web1和web2配置相同

 

安装

# yum install libnl-devel

# tar zxf keepalived-1.2.10.tar.gz

# cd keepalived-1.2.10

#./configure –prefix=/opt/keepalived

#make && make install 

#cp -rf /opt/keepalived/etc/sysconfig/keepalived /etc/sysconfig/

#cp -rf /opt/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/

#cp -rf /opt/keepalived/etc/keepalived/ /etc/

#ln -s /opt/keepalived/sbin/keepalived /sbin/

注:web1和web2都要安装keepalived


配置

主master配置

#/etc/keepalived/keepalived.conf  


global_defs {    router_id LVS_master_1             #定义LVS ID,唯一不能与Slave相同
}
vrrp_sync_group VGM {                               #定义vrrp组
    group {
        VI_CACHE
    }
}

 

  # vrrp 实例配置


vrrp_instance VI_CACHE {
    state MASTER                                     #定义为Master,必须大写
    interface eth0                                   #监控网卡
    lvs_sync_daemon_inteface eth0                    #LVS监听网卡
    virtual_router_id 51                             #虚拟路由
    priority 180                                     #优先级,要比Slave大
    advert_int 5                                     #同步时间间隔
    authentication {                                 #配置认证类型和密码
        auth_type PASS
        auth_pass 7ftWPiTo0pigBLzux14S
    }
    virtual_ipaddress {
        192.168.1.100                                #VIP
    }
}

从Slave配置

#/etc/keepalived/keepalived.conf

global_defs {
    router_id LVS_backup_2
}
    vrrp_sync_group VGM {
    group {
        VI_CACHE
    }
}


# vrrp 实例配置

vrrp_instance VI_CACHE {
    state BACKUP                                 #定义为BACKUP,必须大写
    interface eth0
    lvs_sync_daemon_inteface eth0
    virtual_router_id 51
    priority 150
    advert_int 5
    authentication {
        auth_type PASS
        auth_pass 7ftWPiTo0pigBLzux14S
    }
    virtual_ipaddress {
        192.168.1.100
    }
}

 

注:Keepalived 更多参数详见http://www.keepalived.org/


启动

#/etc/init.d/keepalived start 

 

添加自启动

# vi /etc/rc.local

/etc/init.d/keepalived start

 

故障切换

先停止主keepalvied服务。访问网站.看是否能正常访问,如能正常访问说明keepalived配置成功。