1. 程式人生 > >Nginx負載均衡+Keepalived高可用集群

Nginx負載均衡+Keepalived高可用集群

check list proxy www alived 編譯安裝nginx efi class request

一、搭建環境及軟件版本

負載均衡:Nginx 高可用:Keepalived

Linux:Centos 6.5

Nginx:nginx-1.6.2

Keepalived:keepalived-1.2.13

LB-00:Nginx+Keepalived 192.168.174.40

LB-01:Nginx+Keepalived 192.168.174.41

Web1:LNMP 192.168.174.20

Web2:LAMP 192.168.174.30

二、負載均衡搭建

①解壓編譯安裝Nginx

yum install -y pcre-devel openssl openssl-devel
tar xf nginx-1.6
.2.tar.gz cd nginx-1.6.2 ./configure --prefix=/application/nginx-1.6.3 --user=nginx --group=nginx --with-http_ssl_module --with-http_stub_status_module make && make install ln -s /application/nginx-1.6.3/ /application/nginx cd /application/nginx/conf/

②修改nginx配置文件

upstream bbs_server_pools 後端real-server地址池
在nginx.conf中用include包含
單獨的配置文件,單獨server標簽,
vim nginx.conf
worker_processes  1;
events {
    worker_connections  1024;
}
http {
log_format  main  $remote_addr - $remote_user [$time_local] "$request" 
                      $status $body_bytes_sent "$http_referer" 
                      "$http_user_agent" "$http_x_forwarded_for"
; upstream bbs_server_pools{ server 192.168.174.20; server 192.168.174.30; } include mime.types; #include extra/lb_www.conf; include extra/lb_bbs.conf; #include extra/lb_blog.conf; }
cd extra/
touch lb_bbs.conf lb_www.conf lb_blog.conf
vim lb_bbs.conf 
vim lb_blog.conf 
vim lb_www.conf
server {
        listen       80;
        server_name  bbs.panda.org;
        location / {
                 proxy_pass http://bbs_server_pools;
                 proxy_set_header Host $host;
                 proxy_set_header X-Forwarded-For $remote_addr;
    }
}

③啟動服務

/application/nginx/sbin/nginx 

三、搭建高可用集群

LB-00 為主(master) LB-01 為備(backup)

①yum安裝並配置keepalived

yum install keepalived -y
vim /etc/keepalived/keepalived.conf

技術分享

authentication 認證方式兩邊要一樣

②啟動服務,實現VIP自動漂移

/etc/init.d/keepalived start

技術分享

③開發守護進程腳本(以負載均衡 80端口為例)

vim check_lb_nginx.sh
#!/bin/sh
while true
do
 if [ `netstat -lntup|grep nginx|wc -l` -ne 1 ];then
   /etc/init.d/keepalived stop
 fi
sleep 5
done

後臺運行守護腳本,停止主負載均衡的nginx,VIP立即切換

sh /home/scripts/check_lb_nginx.sh >/dev/null 2>&1 &

技術分享

  技術分享

Nginx負載均衡+Keepalived高可用集群