爲了知足系統的高可用,通常都須要搭建集羣。當主機掛掉的時候,咱們的系統還能夠繼續提供服務。當咱們使用nginx做爲反向代理和動靜分離服務器的時候,也是如此。實現系統的高可用性,是咱們程序員關注的重點。本文介紹了nginx結合keepalived實現主從模式搭建高可用集羣。nginx
本文不做過多的nginx相關配置介紹,默認讀者已經瞭解nginx的相關知識。程序員
Keepalived的做用是檢測服務器的狀態,若是有一臺web服務器宕機,或工做出現故障,Keepalived將檢測到,並將有故障的服務器從系統中剔除,同時使用其餘服務器代替該服務器的工做,當服務器工做正常後Keepalived自動將服務器加入到服務器羣中,這些工做所有自動完成,不須要人工干涉,須要人工作的只是修復故障的服務器。web
yum install pcre-devel zlib zlib-devel openssl openssl-devel
複製代碼
tar zxvf nginx-1.12.2.tar.gz
複製代碼
mkdir -p /usr/local/nginx
./configure --prefix=/usr/local/nginx
複製代碼
make && make install
複製代碼
cd /usr/local/nginx/sbin/
./nginx
./nginx -s stop
./nginx -s start
複製代碼
yum install -y keepalived
複製代碼
vim /etc/keepalived/keepalived.conf
複製代碼
#新增的配置
vrrp_script chk_http_port {
script "/shell/nginx_check.sh" #腳本地址
interval 2 #檢測腳本執行的間隔
weight 2 #比重
}
vrrp_instance VI_1 {
state MASTER #主服務器爲MASTER,從服務器爲BACKUP
interface eth0 #網卡
virtual_router_id 51 #主、備機的virtual_router_id必須相同
priority 100 #主、備機不一樣的優先級,主機優先級較大,備機值較小,默認是100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
#虛擬IP地址
virtual_ipaddress {
192.168.126.88
}
}
複製代碼
mkdir /shell/nginx_check.sh
vim /shell/nginx_check.sh
複製代碼
#!/bin/bash
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
複製代碼
vrrp_instance VI_1 {
state BACKUP #主服務器爲MASTER,從服務器爲BACKUP
interface eth0 #網卡
virtual_router_id 51 #主、備機的virtual_router_id必須相同
priority 50 #主、備機不一樣的優先級,主機優先級較大,備機值較小
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
#虛擬IP地址
virtual_ipaddress {
192.168.126.88
}
}
複製代碼
service keepalived start
複製代碼
ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
link/ether 00:0c:29:4f:31:ce brd ff:ff:ff:ff:ff:ff
inet 192.168.126.100/24 brd 192.168.126.255 scope global eth0
inet 192.168.126.88/32 scope global eth0
inet6 fe80::20c:29ff:fe4f:31ce/64 scope link
valid_lft forever preferred_lft forever
複製代碼
service iptables stop
#查看防火牆是否開機自啓動
chkconfig --list | grep iptables
chkconfig iptables off
複製代碼
http://192.168.126.88/
複製代碼