Linux基礎教程之Keepalived實現Nginx雙主高可用負載均衡集群
實驗目的:使用keepalived實現Nginx的雙主高可用負載均衡集群。
實驗環境:兩臺Nginx proxy(雙主Nginx,各需要兩塊網卡,eth0連接內網,eth1連接外網)、兩臺web server(請求的負載均衡)、一臺client用于驗證結果。
注意:為了不影響實驗結果,在實驗開始前先關閉iptables和seLinux
操作步驟:
一、配置IP
1.配置A主機的IP
# ip addr add dev eth0 192.168.10.2/24
2.配置B主機的IP
# ip addr add dev eth0 192.168.10.23/24
3.配置C主機的IP
# ip addr add dev eth0 192.168.10.3/24
4.配置D主機的IP
# ip addr add dev eth0 192.168.10.33/24
二、配置web服務(C和D主機都做同樣配置,只需修改默認主頁中的IP地址為本機的IP即可,以示區別)
1.安裝apache
# yum -y install apache
2.創建默認主頁
# vim /var/www/html/index.html
<h1>192.168.10.3</h1>
3.啟動apache
# service httpd start
三、配置sorry_server(此服務配置于Nginx proxy主機上,兩臺Nginx proxy都做同樣配置,只需修改默認主頁中的IP地址為本機的IP即可,以示區別)
1.安裝apache
# yum -y install apache
2.創建默認主頁
# vim /var/www/html/index.html
<h1>sorry_server:192.168.10.2</h1>
3.修改監聽端口為8080,以免與nginx所監聽的端口沖突
# vim /etc/httpd/conf/httpd.conf
Listen 8080
4.啟動apache服務
四、配置代理(兩臺Nginx proxy都做同樣配置)
1.安裝nginx
# yum -y install nginx
2.定義upstream集群組,在http{}段中定義;
# vim /etc/nginx/nginx.conf
http {
upstream websrvs {
server 192.168.10.3:80;
server 192.168.10.33:80;
server 127.0.0.1:8080 backup;
}
}
3.調用定義的集群組,在server{}段的location{}段中調用;
# vim /etc/nginx/conf.d/default.conf
server {
location / {
proxy_pass?http://wersrvs;
index index.html;
}
}
4.啟動服務
# service nginx start
五、配置keepalived
A主機上操作
1.安裝keepalived
# yum -y install keepalived
2.編輯A主機的配置文件/etc/keepalived/keepalived.conf,作如下配置:
! Configuration File for keepalived
global_defs {
notification_email {
root@localhost
}
notification_email_from keepalived@localhost
smtp_server 127.0.0.1
smtp_connect_timeout 30
router_id?CentOS6
vrrp_mcast_group4 224.0.100.39
}
vrrp_script chk_down {
script “[[ -f /etc/keepalived/down ]] && exit 1 || exit 0”
interval 1
weight -5
}
vrrp_script chk_nginx {
script “killall -0 nginx && exit 0 || exit 1”
interval 1
weight -5
fall 2
rise 1
}
vrrp_instance ngx {
state MASTER
interface eth1
virtual_router_id 14
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass MDQ41fTp
}
virtual_ipaddress {
192.168.20.100/24 dev eth1
}
track_script {
chk_down
chk_nginx
}
}
vrrp_instance ngx2 {
state BACKUP
interface eth1
virtual_router_id 15
priority 98
advert_int 1
authentication {
auth_type PASS
auth_pass XYZ41fTp
}
virtual_ipaddress {
192.168.20.200/24 dev eth1
}
track_script {
chk_down
chk_nginx
}
}
B主機也作同樣配置,稍作修改即可,需要修改的地方如下:
vrrp_instance ngx {
state BACKUP
priority 98
}
vrrp_instance ngx2 {
state MASTER
priority 100
}
六、模擬故障,驗證結果
1.啟動兩臺Nginx proxy的keepalived服務
# service keepalived start
2.訪問192.168.20.100,結果應是后端的web server輪詢響應請求
3.訪問192.168.20.200,結果應是后端的web server輪詢響應請求
4.將后端的web server關閉一臺,訪問192.168.20.100或192.168.20.200,響應請求的將只是另一臺正常運行web server的主機
5.將后端的web server都關閉,此時訪問192.168.20.100或192.168.20.200,響應請求的將只是Nginx proxy中定義的主server中的sorry_server
6.關閉一臺Nginx proxy 的nginx服務,備server將把IP地址添加到本機,繼續提供服務,此時訪問192.168.20.100或192.168.20.200并不會有任何察覺