(1)準備三臺服務器nginx
正常來講,應該準備四臺,兩臺安裝ngnix+keeplived實現高可用以及負載均衡,兩臺作節點服務器,這裏78充當一臺節點服務器,172.31.113.77(nginx+keepalived),172.31.113.78(nginx+keepalived+tomcat),172.31.113.79(tomcat)。vim
(2)安裝nginx服務器tomcat
77,78服務器安裝ngnix以及配置負載均衡能夠查看以前的博文。bash
(3)77節點,安裝keepalived服務器
1.首先安裝keepalived rpm包:popt 以及popt-devel。負載均衡
2.下載keepalived安裝包jsp
cd /usr/local wget http://www.keepalived.org/software/keepalived-1.2.8.tar.gz
3.解壓並編譯keepalived測試
tar zvxf /usr/local keepalived-1.2.8.tar.gz cd /usr/local/keepalived-1.2.8 ./configure --prefix=/usr/local/keepalived --sysconf=/etc
執行編輯的時候會報以下Openssl錯誤:spa
configure: error: !!! OpenSSL is not properly installed on your system. !!! !!! Can not include OpenSSL headers files. !!!
解決方案:http://kusix.iteye.com/blog/1226892rest
4.編譯並安裝
make && make install
5.啓動keepalived
cp /usr/local/keepalived/sbin/keepalived /bin/ chkconfig --add keepalived #設置開機啓動 chkconfig keepalived on #啓動keepalive服務 /etc/init.d/keepalived start
(4)配置keepalived
cp /etc/keepalived/keepalived.conf /etc/keepalived/keepalived.conf_bak
vim /etc/keepalived/keepalived.conf
(1)配置MASTER節點
global_defs { notification_email { acassen@firewall.loc failover@firewall.loc sysadmin@firewall.loc } notification_email_from Alexandre.Cassen@firewall.loc smtp_server 192.168.200.1 smtp_connect_timeout 30 router_id LVS_DEVEL } vrrp_script Monitor_Nginx { script "/root/monitor_nginx.sh" #執行腳本路徑 interval 2 weight 2 } vrrp_instance VI_1 { state MASTER #標識爲MASTER節點,從節點標識BACKUP interface eth0 virtual_router_id 51 #兩個節點的ID須要一致 priority 100 #主、備機取不一樣的優先級,主機值較大,備份機值較小,值越大優先級越高 advert_int 1 authentication { auth_type PASS auth_pass 1111 } virtual_ipaddress { 172.31.113.110 #虛擬IP } track_script { Monitor_Nginx #執行腳本名字 } }
(2)編輯監控腳本monitor_nginx.sh,vim /root/monitor_nginx.sh,內容以下,並賦予執行權限:chmod +x /root/monitor_nginx.sh
#!/bin/bash counter=$(ps -C nginx --no-heading|wc -l) if [ "${counter}" = "0" ]; then # /usr/local/nginx/sbin/nginx # sleep 2 # counter=$(ps -C nginx --no-heading|wc -l) # if [ "${counter}" = "0" ]; then /etc/init.d/keepalived stop # fi fi
到此,keepalived的安裝以及配置結束,78備用節點重複上面的操做,只是把配置文件keepalived.conf中的state修改成BACKUP , priority比MASTER稍低便可。
(5)分別啓動keepalived,nginx,以及tomcat服務器。
service keepalived restart
在主服務器即78節點,能夠經過 ip a查看虛擬IP,顯示以下:
(6)測試nginx+keepalive實現高可用
訪問172.31.113.110/index.jsp,首先將77服務器的nginx進程殺掉,查看77的keepalived進行也被中止掉了(由於上面咱們的腳本當nginx爲零的時候,中止keepalived,只有中止keepalived,78備用服務器才能獲得虛擬IP),這時候查看78的虛擬IP也爲172.31.113.110,繼續對外提供服務。
總結:這種方案只能實現當主節點的nginx進程結束了,主節點的腳本monitor_nginx.sh執行後,中止keepalived進程,備用節點才能獲得虛擬IP,進而對外繼續提供服務。後面測試了一下,直接關閉主節點,備用節點沒法獲得虛擬IP,沒法對外服務。因此當主節點直接宕機的話,這種方案就不可行了,難道這種方案就是高可用?百度搜了很久,都是這樣實現的。