为什么要使用keepalived
Nginx作为反向代理服务器实现服务器分配资源负载均衡,但是如果有一天Nginx服务器宕机了,那用户的请求如何发送到服务器来呢?于是,keepalived作为检查服务器状态的软件来了!
主备模式搭建
整体架构图
172.16.10.185 模拟web服务器1
172.16.10.189 模拟web服务器2
172.16.10.186 keepalived + nginx 负载均衡服务器1
172.16.10.184 keepalived + nginx 负载均衡服务器2
172.16.10.190 模拟客户端测试
添加epel源:
curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo
四台机器关闭防火墙安装nginx:
systemctl stop firewalld //关闭防火墙
sed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux //关闭selinux,重启生效
setenforce 0 //关闭selinux,临时生效
ntpdate 0.centos.pool.ntp.org //时间同步
yum install nginx -y //安装nginx
两台模拟web修改
# vim /etc/nginx/nginx.conf //编辑配置文件
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
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;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name www.zhubing.com;
location / {
root /usr/share/nginx/html;
}
access_log /var/log/nginx/access.log main;
}
}
两台LB服务器
# vim /etc/nginx/nginx.conf
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
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;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
upstream backend {
server 172.16.10.185:80 weight=1 max_fails=3 fail_timeout=20s;
server 172.16.10.189:80 weight=1 max_fails=3 fail_timeout=20s;
}
server {
listen 80;
server_name www.mtian.org;
location / {
proxy_pass http://backend;
proxy_set_header Host $host:$proxy_port;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
}
检测nginx配置文件语法是否正确
nginx -t
测试机器 配置域名解析
vim /etc/hosts
测试,看到均衡负载,证明nginx搭建成功
搭建keepalived,两台LB服务器
yum install -y keepalived
主:vim /etc/keepalived/keepalived.conf
注意 interface 属性 需要设置成自己的网卡名
从:vim /etc/keepalived/keepalived.conf
启动 keepalived
systemctl start keepalived
查看状态
systemctl status keepalived
我的查看状态发现dead状态
查看日志重启,需要开两个终端
tail -f /var/log/message
systemctl restart keepalived
发现interface 配置错了,
小插曲:如果发现启动不了,不要慌,tail -f /var/log/message 查看日志
启动之后 查看ip(主)
[root@k8s-slave2 nginx] ip a
我们在测试机上访问 vip
从机
因为从设置的是backup模式,所以不会出现vip,只有当主keepalived 挂掉,就会漂移到从机
systemctl stop keepalived.service
在从服务器中出现vip
访问vip依旧是通的
至此Keepalived+Nginx高可用主备模式搭建成功!