nginx+keepalived实现高可用

实验环境

192.168.186.100 虚拟vip
192.168.186.129 centos7 安装nginx、keepalived的服务器
192.168.186.130 centos7 安装nginx、keepalived的服务器
192.168.186.128 centos7 提供真实服务的httpd服务器
192.168.186.131 centos7 提供真实服务的httpd服务器
本地windows

关闭防火墙和selinux

systemctl stop firewalld
setenforce 0

httpd服务器配置

yum install httpd -y
#在/etc/httpd/conf/httpd.conf修改httpd端口
listen 8080
#在192.168.186.128的/var/www/html中创建a.html,向里面写入web1,在192.168.186.131的/var/www/html中创建a.html,向里面写入web2
echo web1 > a.html
echo web2 > a.html
#启动服务
systemctl start httpd

nginx负载均衡器配置

nginx配置

upstream myserver {
server 192.168.186.128:8080;
server 192.168.186.131:8080;
}
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name 192.168.186.100;
root /usr/share/nginx/html;

# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;

location / {
proxy_pass http://myserver/a.html;
}
}

keepalived配置

#192.168.186.128配置
global_defs {
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 51
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.186.100
}
}
#192.168.186.131配置
global_defs {
router_id LVS_DEVEL
}
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 51
priority 99
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
192.168.186.100
}
}

查看虚拟vip是否生成、是否能够自动漂移

#在MASTER主机上使用ip address命令查看ens33网卡下是否存在192.168.186.100
ip address
#ping 192.168.186.100是否通
ping 192.168.186.100
#停止MASTER主机的keepalived,查看虚拟ip是否漂移到BACKUP主机
systemctl stop keepalived
ip address

测试

在windows浏览器输入192.168.186.100:80,成功轮询访问到真实httpd服务器的页面