keepalived主机:192.168.174.129
keepalived备机:192.168.174.130
realserver1:192.168.174.128(nginx服务器,首页为hello world)
realserver2:192.168.174.133(nginx服务器,首页为nginx默认首页)
VIP:192.168.174.222
LVS模式:DR
防火墙iptables处于关闭状态,selinux为disabled
安装lvs:可以直接使用本地yum安装

yum -y install ipvsadm

linux下lvs+keepalived安装配置
安装keepalived:
下载keepalived源码安装包并解压
linux下lvs+keepalived安装配置_第1张图片
进入keepalived解压目录,执行

./configure --prefix=/usr/local/keepalived

linux下lvs+keepalived安装配置
编译配置完成后,执行make && make install
拷贝keepalived启动文件到/etc/init.d/下,网上教程有的从安装目录下拷贝过来的,我在安装目录下没有找到相关文件
linux下lvs+keepalived安装配置
执行,对于这两步不太了解

cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/

linux下lvs+keepalived安装配置

cp /usr/local/keepalived/sbin/keepalived /usr/sbin/

linux下lvs+keepalived安装配置
新建文件夹/etc/keepalived

mkdir /etc/keepalived

将keepalived的配置文件拷贝过来,keepalived启动时会从/etc/keepalived目录下查找keepalived.conf配置文件,如果没有找到则使用默认的配置。

cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/

linux下lvs+keepalived安装配置
以上操作在keepalived主机和从机上皆操作
修改主机配置文件
linux下lvs+keepalived安装配置_第2张图片
修改备机配置文件
linux下lvs+keepalived安装配置_第3张图片
主机和备机配置文件只有router_id和vrrp_instance的state和priority不同
修改/etc/hosts文件,将两台realserver加入进来
linux下lvs+keepalived安装配置_第4张图片
打开主机和备机的路由交换功能

echo 1 >/proc/sys/net/ipv4/ip_forward

linux下lvs+keepalived安装配置
启动主机和备机上的keepalived服务

service keepalived start

linux下lvs+keepalived安装配置
查看虚拟ip状态
linux下lvs+keepalived安装配置
在两台realserver上建立脚本文件,每台一个,内容一样,主要作用是绑定虚拟ip到环回接口
linux下lvs+keepalived安装配置_第5张图片
执行脚本/opt/script/lvs_real.sh start
查看ip状态
linux下lvs+keepalived安装配置_第6张图片
注意lo:0,绑定成功
在本地浏览器访问虚拟ip192.168.174.222,成功
linux下lvs+keepalived安装配置_第7张图片
查看主机上的虚拟ip状态
linux下lvs+keepalived安装配置_第8张图片
在主机上停掉keepalived主机的keepalived服务

killall keepalived

linux下lvs+keepalived安装配置
本地浏览器再次访问虚拟ip,发现正常访问
linux下lvs+keepalived安装配置_第9张图片
查看备机上的虚拟ip状态,发现成功漂移过来
linux下lvs+keepalived安装配置_第10张图片
成功
停掉realserver2的nginx服务,再次访问虚拟ip,可以发现显示的是realsever1的内容,我的realserver1和realserver2为了便于区分首页有一点不同
linux下lvs+keepalived安装配置
linux下lvs+keepalived安装配置_第11张图片