#Nginx+keepalived雙機熱備前端
標籤(空格分隔):linux,nginx,keepalivedlinux
Keepalived 是一種高性能的服務器高可用或熱備解決方案,Keepalived能夠用來防止服務器單點故障(單點故障是指一旦某一點出現故障就會致使整個系統架構的不可用)的發生,經過配合Nginx能夠實現web前端服務的高可用。nginx
Keepalived實現的基礎是VRRP協議,Keepalived就是巧用VRRP協議來實現高可用性(HA)的.web
VRRP(Virtual Router Redundancy Protocol)協議是用於實現路由器冗餘的協議,VRRP協議將兩臺或多臺路由器設備虛擬成一個設備,對外提供虛擬路由器ip(一個或多個),而在路由器組內部,若是實際擁有這個對外IP的路由器若是工做正常的話就是MASTER,或者是經過算法選舉產生,MASTER實現針對虛擬路由器IP的各類網絡功能,如arp請求,ICMP,以及數據的轉發等;其餘設備不擁有該IP,狀態是BACKUP,除了接收MASTER的VRRP狀態通告信息外,不執行對外的網絡功能。當主機失效時,BACKUP將接管原先MASTER的網絡功能。算法
VRRP協議使用多播數據來傳輸VRRP數據,VRRP數據使用特殊的虛擬源MAC地址發送數據而不是自身網卡的MAC地址,VRRP運行時只有MASTER路由器定時發送VRRP通告信息,表示MASTER工做正常以及虛擬路由器IP(組),BACKUP只接收VRRP數據,不發送數據,若是必定時間內沒有接收到MASTER的通告信息,各BACKUP將宣告本身成爲MASTER,發送通告信息,從新進行MASTER選舉狀態。bash
cd /home wget http://www.keepalived.org/software/keepalived-1.2.18.tar.gz tar -zxvf keepalived-1.2.18.tar.gz cd keepalived-1.2.18/ ./configure --prefix=/usr/local/keepalived make && make install cp /usr/local/keepalived/sbin/keepalived /usr/sbin/ 複製keepalived啓動文件到默認路徑,也能夠經過設置環境變量的path實現 cp /usr/local/keepalived/etc/rc.d/init.d/keepalived /etc/init.d/ 複製服務啓動腳本到,以即可以經過service控制keepalived服務 cp /usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/ 複製keepalived服務腳本到默認的地址,也經過修改init.d/keepalived文件中的相應配置實現 mkdir -p /etc/etc/keepalived/ cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/ vi /etc/keepalived/keepalived.conf 複製默認配置文件到默認路徑,其實也能夠在/etc/init.d/keepalived中設置路徑 chkconfig keepalived on 開機啓動服務
主: 192.168.135.128 從: 192.168.135.143 虛擬IP: 192.168.135.211
global_defs { # 路由節點 host對應 127.0.0.1 nginx_master router_id nginx_master } vrrp_script chk_http_port { script "/usr/local/keepalived/nginx.sh" #在這裏添加腳本連接 interval 2 #腳本執行間隔 weight -20 #腳本結果致使的優先級變動 } vrrp_instance VI_NODE { state MASTER interface eth0 virtual_router_id 100 mcast_src_ip 192.168.135.128 # 主 ip priority 100 # 初始值權重 advert_int 1 authentication { auth_type PASS auth_pass 123456 } track_script { chk_http_port #添加腳本執行 } virtual_ipaddress { 192.168.135.211 # 虛擬IP } }
global_defs { # 路由節點 路由節點 host對應 127.0.0.1 nginx_slave router_id nginx_slave } vrrp_script chk_http_port { script "/usr/local/keepalived/nginx.sh" #在這裏添加腳本連接 interval 2 #腳本執行間隔 weight -20 #腳本結果致使的優先級變動 } vrrp_instance VI_NODE { state BACKUP interface eth1 # 網卡 ip a 查看 virtual_router_id 100 mcast_src_ip 192.168.135.143 # 從IP priority 80 # 初始值權重 advert_int 1 authentication { auth_type PASS # 驗證方式 auth_pass 123456 # 密碼 } track_script { chk_http_port #添加腳本執行 } virtual_ipaddress { 192.168.135.211 # 虛擬IP } }
#!/bin/bash A=`ps -C nginx –no-header |wc -l` if [ $A -eq 0 ];then /usr/local/nginx/sbin/nginx #nginx命令的路徑 sleep 3 if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then killall keepalived fi fi
注意點: 1 虛擬ip要根據網卡設定 服務器
2 nginx.sh 加權限 chmod +x /nginx.sh 3 priority 80 這個權重注意下
1 開啓主和從的keep和nginx service keepalived start ./nginx
2 關閉主nginx服務