blog/linux/centos7安装keepalived实现负载均衡

环境配置

node1 192.168.10.111node2 192.168.10.112
keeplived + nginxkeeplived + nginx

安装keeplived

yum install -y openssl openssl-devel
wget http://tar.matosiki.site/tar/keepalived-2.0.0.tar.gz
tar -zxvf keepalived-2.0.0.tar.gz -C /usr/local/
cd /usr/local/keepalived-2.0.0/ && ./configure --prefix=/usr/local/keepalived
make && make install

keeplived做成服务

mkdir -p /etc/keepalived
cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/

cp /usr/local/keepalived-2.0.0/keepalived/etc/init.d/keepalived /etc/init.d/
cp /usr/local/keepalived-2.0.0/keepalived/etc/sysconfig/keepalived /etc/sysconfig/

ln -s /usr/local/sbin/keepalived /usr/sbin/
# ln -s /usr/local/keepalived/sbin/keepalived /sbin/

chmod 755 /etc/init.d/keepalived
chkconfig keepalived on

更改节点1配置文件

vi /etc/keepalived/keepalived.conf
global_defs {
router_id NODE1 # 更改路由编号
}
vrrp_script chk_http_port {
script "/etc/keepalived/nginx_check.sh" # 检查脚本
interval 2
weight -20 # 权重减20
}
vrrp_instance VI_1 {
state MASTER # 主节点为MASTER,备份节点为BACKUP
interface ens33 # 网卡名称
virtual_router_id 50 #虚拟路由编号
priority 100 # 优先级配置0-254
advert_int 1 # 组播信息发送间隔,两个节点必须配置一致,默认1s
authentication {
auth_type PASS
auth_pass matosiki # 真实生产环境下对密码进行匹配
}
track_script {
chk_http_port
}
virtual_ipaddress {
192.168.10.66/24 # 虚拟ip(vip),可以指定多个 两个节点保持一直
}
}

节点2配置

global_defs {
router_id NODE2
}

vrrp_script chk_http_port {
script "/etc/keepalived/nginx_check.sh"
interval 2
weight -20
}

vrrp_instance VI_1 {
state BACKUP
interface ens33
virtual_router_id 50
priority 90
advert_int 1
authentication {
auth_type PASS
auth_pass matosiki
}
track_script {
chk_http_port
}
virtual_ipaddress {
192.168.10.66/24
}
}

两台机器上编写 nginx_check.sh脚本

vi /etc/keepalived/nginx_check.sh
A=`ps -C nginx –no-header |wc -l`
if [ $A -eq 0 ];
then
/usr/local/nginx/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];
then
killall keepalived
fi
fi
chmod +x /etc/keepalived/nginx_check.sh
service keepalived start
ip a
ps -ef | grep nginx
ps -ef | grep keepalived

【问题】 在vmware有动态ip也有静态ip设置vip为192.168.10.66 开始可以访问重启
keeplived服务后就无法ping通了
【解决】
vi /etc/keepalived/keepalived.conf
注释掉vrrp_strict

本文总阅读量