Nginx+keepalived实现高可用

安装openresty

openresty安装步骤参照这里

安装Keepalived

Centos 6编译安装ipvsadm-1.26

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
[root@vpsback software]# uname -r

2.6.32-696.30.1.el6.x86_64

yum install -y kernel-devel-2.6.32-696.30.1.el6.x86_64

ln -s /usr/src/kernels/2.6.32-696.30.1.el6.x86_64/ /usr/src/linux

yum -y install popt popt-devel libnl libnl-devel popt-static

tar xzvf ipvsadm-1.26.tar.gz

cd ipvsadm-1.26

make

make install

[root@vpsback ipvsadm-1.26]# ipvsadm --version

ipvsadm v1.26 2008/5/15 (compiled with popt and IPVS v1.2.1)

[root@vpsback ipvsadm-1.26]# ipvsadm -ln

IP Virtual Server version 1.2.1 (size=4096)

Prot LocalAddress:Port Scheduler Flags

-> RemoteAddress:Port Forward Weight ActiveConn InActConn

安装keepalived软件

1
2
3
4
5
 tar zxvf keepalived-1.3.5.tar.gz 
cd ikeepalived-1.3.5
./configure --prefix=/usr/local/keepalived --with-kernel-dir=/usr/src/kernels/2.6.32-696.30.1.el6.x86_64
make
make install

配置和启动keepalived

1
2
mkdir  /etc/keepalived
vi /etc/keepalived/keepalived.conf

keepalived.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
! Configuration File for keepalived

global_defs {
notification_email {
acassen
}
notification_email_from Alexandre.Cassen@firewall.loc
smtp_server 192.168.200.1
smtp_connect_timeout 30
router_id LVS_DEVEL
}

vrrp_script chk_nginx {
script "/etc/keepalived/check_nginx.sh"
interval 2
weight -5
fall 3
rise 2
}


vrrp_instance VI_1 {
state MASTER ##备用keepalived配置为BACKUP
interface eth0
virtual_router_id 50 #虚拟路由标示,相同实例,需相同标示。
nopreempt
priority 100 #优先级 数字越大 优先级越高 MASTER的优先级高于BACKUP优先级(如master 100,backup 50)
advert_int 1
virtual_ipaddress {
192.168.1.230 ##设定虚拟IP地址 可以设置多个 每行一个
}
}

/etc/keepalived/nginx_check.sh内容如下

1
2
3
4
5
6
7
8
9
#!/bin/bash
A=`ps -C nginx –no-header |wc -l`
if [ $A -eq 0 ];then
/usr/servers/nginx/sbin/nginx
sleep 2
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
killall keepalived
fi
fi

启动keepalived

1
/usr/servers/keepalived/sbin/keepalived

查看虚拟IP和真实IP的状态

1
2
3
4
[root@localhost keepalived]# ip a | grep eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
inet 192.168.1.231/24 brd 192.168.1.255 scope global eth0
inet 192.168.1.230/32 scope global eth0

重启keepalived

1
/usr/servers/keepalived/sbin/keepalived --signum=reload

通过浏览器访问http://192.168.1.230:81/查看是否请求到了http://192.168.1.231:81/

谢谢你请我吃糖果