用Keepalived搭建雙Nginx server集群,防止單點故障
浏覽器訪問虛擬IP: 192.168.1.57, 該虛擬IP被Keepalived接管,兩個Keepalived進程分別運行在物理IP為192.168.1.56和192.168.1.59服務器上,這兩個服務器上都運行著Nginx server。Nginx server都監聽虛擬IP 192.168.1.57. Nginx背後有一些web app集群,已經配置成upstream.
為了防止Nginx自己成為單點瓶頸,這裡采用了雙Nginx server的方式。每個Server都是Ubuntu 12.04.
假定我的第一台Ubuntu server物理IP地址是192.168.1.56,已經安裝了Nginx server,現在安裝Keepalived,後面稱這台為master server.
[plain]
apt-get install keepalived
另外一台Ubuntu server物理IP是192.168.1.59, 也安裝Nginx server和Keapalived. 後面稱這台為backup server. Nginx的安裝以及配置不是本文關注內容,請參考我的其他文章。
現在開始配置master server. 安裝完成keepalived後,通過查看腳本/etc/init.d/keepalived裡面發現,啟動配置文件的路徑是
[plain]
CONFIG=/etc/keepalived/keepalived.conf
但是該文件現在還不存在。所以我創建一個,內容如下:
[plain]
# Settings for notifications
global_defs {
notification_email {
[email protected] # Email address for notifications
}
notification_email_from keepalived@your_company.com # The from address for the notifications
smtp_server 127.0.0.1
smtp_connect_timeout 15
}
# Define the script used to check if haproxy is still working
vrrp_script chk_http_port {
script "/etc/keepalived/check_nginx.sh" # check Nginx is alive or not
interval 2 #
weight 2
}
# Configuation for the virtual interface
vrrp_instance VI_1 {
interface eth0
state MASTER # set this to BACKUP on the other machine
priority 101 # set this to 100 on the other machine
virtual_router_id 51
smtp_alert # Activate email notifications
authentication {
auth_type PASS
auth_pass 1111 # Set this to some secret phrase
}
# The virtual ip address shared between the two loadbalancers
virtual_ipaddress {
192.168.1.57
}
# Use the script above to check if we should fail over
track_script {
chk_http_port
}
}
說明:
1. smtp_server必須要用127.0.0.1
2. 自己要創建一個檢查nginx進程的腳本
[plain]
/etc/keepalived/check_nginx.sh
內容如下:
[plain]
!/bin/bash
# try to start nginx if nginx process is dead
# shutdonw keepalived process if start nginx failed
pid=`ps -C nginx --no-header |wc -l`
if [ $pid -eq 0 ];then
service nginx start
sleep 3
if [ `ps -C nginx --no-header |wc -l` -eq 0 ];then
service keepalived stop
fi
fi
3. 修改nginx的所有server配置,將server_name都改為虛擬IP
[plain]
server_name 192.168.1.57;
4. 注意,這裡的虛擬IP不是用修改/etc/network/interfaces的方式,而是在keepalived配置文件中直接設置,要想判斷是否成功,直接ping 就行了,ifconfig是看不到的。
[plain]
ping 192.168.1.57
PING 192.168.1.57 (192.168.1.57) 56(84) bytes of data.
64 bytes from 192.168.1.57: icmp_req=1 ttl=64 time=0.024 ms
64 bytes from 192.168.1.57: icmp_req=2 ttl=64 time=0.020 ms
對192.168.1.59做相同的配置,略有變化的是:
[plain]
vrrp_instance VI_1 {
interface eth0
state BACKUP // changed
priority 100 // changed
通過輪流關閉master和backup,證明keepalived已經有效工作了。