nginx+keepalived高可用
规划
nginx+keepalived 主 192.168.57.3
nginx+keepalived备 192.168.57.4
VIP 192.168.57.100
nginx1 192.168.57.5
nginx2 192.168.57.6
所有机器上安装nginx服务
[root@master ~]# cat /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/7/$basearch/
gpgcheck=0
enabled=1
gpgkey=http://nginx.org/keys/nginx_signing.key
主备机器上安装keepalived,需要先安装epel源
yum install -y keepalived
配置keepalived
[root@master ~]# cat /etc/keepalived/keepalived.conf
! Configuration File for keepalived
global_defs {
notification_email {
root@local
xxx@xx.com
}
notification_email_from root@local
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id nginx_keepalived
}
vrrp_script chk_nginx {
script /etc/keepalived/nginx_check.sh
interval 2
weight -20
}
vrrp_instance VI_1 {
state MASTER #从节点这里配置BACKUP
interface enp0s8
virtual_router_id 50
priority 100 #从节点这里配置90,这个代表优先级,越大优先级越高
nopreempt
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
track_script {
chk_nginx
}
virtual_ipaddress {
192.168.57.100/24 dev enp0s8
}
}
主备机器上配置nginx
[root@master ~]# cat /etc/nginx/conf.d/default.conf
upstream backend {
server 192.168.57.5:80 weight=1 max_fails=3 fail_timeout=20s;
server 192.168.57.6:80 weight=1 max_fails=3 fail_timeout=20s;
}
server {
listen 80;
server_name l92.168.57.100;
location / {
proxy_pass http://backend;
proxy_set_header Host $host:$proxy_port;
proxy_set_header X-Forwarded-For $remote_addr;
}
配置检测脚本
[root@master ~]# cat /etc/keepalived/nginx_check.sh
#!/bin/bash
while true
do
if [ $(netstat -tlnpgrep nginxwc -l) -ne 1 ]
then
systemctl stop keepalived
fi
sleep 2
done
添加执行权限,并启动nginx和keepalived
chmod +x /etc/keepalived/nginx_check.sh
systemctl start nginx
systemctl start keepalived
nginx1和nginx2上配置nginx
[root@realserver2 ~]# echo realserver2 >/usr/share/nginx/html/index.html
[root@realserver2 ~]# systemctl start nginx
[root@realserver2 ~]# systemctl enable nginx
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
[root@realserver2 ~]#
[root@realserver1 ~]# echo realserver1 >/usr/share/nginx/html/index.html
[root@realserver1 ~]# systemctl start nginx
[root@realserver1 ~]# systemctl enable nginx
Created symlink from /etc/systemd/system/multi-user.target.wants/nginx.service to /usr/lib/systemd/system/nginx.service.
[root@realserver1 ~]#
配置完毕,启动测试,curl http://192.168.57.100
nginx+keepalived高可用
http://www.jcwit.com/article/32/