Nginx+keepalived負載均衡

 

一、安裝Nginx

$ yum -y install gcc            # nginx是c寫的javascript

$ yum -y install pcre-devel   # url重寫用到的包php

$ yum -y install zlib  zlib-devel    # 解壓縮用到的包css

 

擴展①:html

yum install -y lsof前端

lsof -i:80 #在nginx啓動前,須要先檢查端口是否被佔用java

 

yum install elinks   # 除了elinks還有curl、lynx等文本瀏覽器nginx

elinks  http://192.168.229.10 -dumpweb

 

安裝killall命令算法

yum search killallspring

yum -y install psmisc

 

二、虛擬主機

2.一、基於IP的虛擬主機

2.二、基於端口的虛擬主機

2.三、基於域名的虛擬主機

vim /etc/hosts

 

 驗證:

 

三、長鏈接

# 關閉長鏈接:0表明關閉

keepalive_timeout 0;

# 開啓長鏈接(默認開啓)

# keepalive_timeout 65;

# 一個長鏈接處理最大請求數(按期釋放內存,防止內存溢出)

# keepalive_requests 8192;

 

四、壓縮優化(數據壓縮)

gzip on;        # 啓動gzip壓縮功能

gzip_proxied any;    # nginx作前端代理時啓用該選項,表示不管後端服務器的headers返回什麼信息,都無條件啓用壓縮

gzip_min_length 1k;   # 小於1k的小文件不壓縮(小文件可能會越壓縮越大)

gzip_buffers 4 8k;     # 設置系統獲取幾個單位的緩存用於存儲gzip的壓縮結果數據流,按照原始數據大小以8k爲單位申請4倍內存空間

gzip_comp_level 6;    # gzip壓縮級別,1壓縮比最小處理速度最快,9壓縮比最大處理最慢也最消耗CPU,通常設置爲3便可

gzip_types text/plain text/css text/xml  text/javascript application/javascript application/json application/x-javascript application/xml application/xml+rss image/jpeg image/gif image/png;   # 頁面或文檔啓用壓縮類型

gzip_vary on;         # 開啓在http header中添加Vary:Accept-Encoding

 

五、客戶端緩存優化

語法:expires [time|epoch|max|off]

默認值:expires off

做用域:http,server,locatio

# 客戶端緩存設置:png或gif文件在客戶端緩存一個小時

location ~* \.(png|gif)$ {

       expires 1h;

}

測試瀏覽器刷新以Chrome爲例:

①ctrl+f5:

清空本地緩存從服務器拿數據。

②F5或者 點擊 瀏覽器的刷新圖標:

優先從本地找,而後去找服務器覈對信息是否一致。從本地拿數據。

③回車:

從本地緩存拿數據。

六、Nginx分發算法

集羣分發算法:如何將用戶請求按照必定的規律分發給業務服務器。主要分爲Nginx集羣默認算法和基於請求頭分發算法。

nginx的upstream 目前支持4種方式的分配:

(1)輪詢(默認)

每一個請求按時間順序逐一分配到不一樣的後端服務器,若是後端服務器down掉,能自動剔除。

upstream backend {

   # no load balancing method is specified for Round Robin

   server backend1.example.com weight=1;

   server backend2.example.com;

}

 

(2)最小鏈接數

指定輪詢概率,weight和訪問比率成正比,用於後端服務器性能不均的狀況。

upstream backend {

    least_conn;

    server backend1.example.com weight=1;

    server backend2.example.com;

}

 

(1)和(2):指定輪詢概率(weight),weight和訪問比率成正比,用於後端服務器性能不均的狀況。

 

(3)ip_hash

每一個請求按訪問ip的hash結果分配,這樣每一個訪客固定訪問一個後端服務,好處是能夠解決session的問題。

所以前兩種只能處理靜態頁面,而這種方式能夠處理動態網站。

upstream backend {

    ip_hash;

    server backend1.example.com;

    server backend2.example.com;

}

 

若是其中一臺服務須要臨時移除

upstream backend {

    server backend1.example.com;

    server backend2.example.com;

    server backend3.example.com down;

}

 

(4)通用hash

 

upstream backend {

    hash $request_uri consistent;

    server backend1.example.com;

    server backend2.example.com;

}

 

(5)最少時間(收費)

按後端服務器的響應時間來分配請求,響應時間短的優先分配。

least_time的參數:

header    – Time to receive the first byte from the server

last_byte       – Time to receive the full response from the server

last_byte inflight  – Time to receive the full response from the server, taking into account incomplete requests

 

upstream backend {

    least_time header;

    server backend1.example.com;

    server backend2.example.com;

}

 

(6)隨機(收費)

least_conn     – The least number of active connections

least_time=header       (NGINX Plus) – The least average time to receive the response header from the server ($upstream_header_time)

least_time=last_byte     (NGINX Plus) – The least average time to receive the full response from the server ($upstream_response_time)

 

upstream backend {

    random two least_time=last_byte;

    server backend1.example.com;

    server backend2.example.com;

    server backend3.example.com;

    server backend4.example.com;

}

 

七、Nginx基於請求頭的分發

7.一、基於host分發

基於host分發這種分發方式適用於多集羣分發。例如:一個公司有多個網站,每一個網站就是一個集羣。

7.二、基於開發語言分發

這種分發方式適用於混合開發的網站,某些大型網站既有php也有jsp,就能夠基於開發語言分發。

7.三、基於瀏覽器的分發

這種基於瀏覽器的分發,常應用於PC端和移動端區分或瀏覽器適配。

7.四、基於源IP分發

像騰訊新聞、58同城等等網站,每每在什麼地方登錄則獲取哪一個地方的數據。服務器經過源IP匹配判斷,從對應的數據庫中獲取數據。

7.4.一、geo模塊

Nginx的geo模塊不只能夠有限速白名單的做用,還能夠作全局負載均衡,能夠要根據客戶端ip訪問到不一樣的server。

geo指令是經過ngx_http_geo_module模塊提供的。默認狀況下,nginx安裝時是會自動加載這個模塊,除非安裝時人爲的手動添加--without-http_geo_module。

ngx_http_geo_module模塊能夠用來建立變量,其值依賴於客戶端IP地址。

7.4.二、geo模塊

upstream bj.server {

    server 192.168.31.42;    # web01

}

upstream sh.server {

    server 192.168.31.43;      # web02

}

upstream default.server {

    server 192.168.31.42:81;      # web03

}

geo $geo {       # IP庫

    default default;

    192.168.31.241/32 bj;   # 北京

    192.168.31.242/32 sh;   # 上海

}

server {

    listen  80;

    server_name   www.web1.com;

 

    location / {

        proxy_pass http://$geo.server$request_uri;

    }

}

 

八、keepalived+nginx 高可用集羣

8.一、架構圖

 

 

8.二、修改cat /etc/hosts

192.168.229.11 ha1

192.168.229.12 ha2

192.168.229.13 ha3

192.168.229.14 ha4

192.168.229.15 ha5

 

8.三、服務器免密碼登陸

ssh-keygen -t rsa  #一直Enter

ssh-copy-id -i /root/.ssh/id_rsa.pub root@ha1

 

8.四、Keepalived介紹

Keepalived的做用是檢測服務器的狀態,

當服務器宕機或工做出現故障,Keepalived將檢測到並將服務器集羣中剔除,選擇其餘服務器代替該服務器的工做;

當服務器恢復工做正常,Keepalived檢測到自動將服務器加入服務器羣集羣。

總結來講:Keepalived軟件是一個監控+自愈的軟件。

運行協議是VRRP,主分發器的keepalived會向網絡廣播。

8.五、Keepalived安裝

下載:keepalived-2.0.10.tar.gz 

依賴:yum install -y kernel-devel 

編譯與安裝:

cd keepalived-2.0.10

./configure --prefix=/usr/local/keepalived

make

make install 

服務配置:

mkdir /etc/keepalived

cp /usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/

ln -s /usr/local/keepalived/sbin/keepalived /sbin/

 

8.六、keepalived配置

! Configuration File for keepalived

 

global_defs {

   notification_email {

     acassen@firewall.loc

     failover@firewall.loc

     sysadmin@firewall.loc

   }

   notification_email_from Alexandre.Cassen@firewall.loc

   smtp_server 127.0.0.1

   smtp_connect_timeout 30

   router_id LVS_DEVEL

   vrrp_skip_check_adv_addr

   vrrp_strict

   vrrp_garp_interval 0

   vrrp_gna_interval 0

}

 

vrrp_script check_nginx{

        script "/etc/keepalived/check-nginx.sh"

        interval 2

#       timeout 1

        fall 1

}

 

vrrp_instance nginx {

    state MASTER

    interface eth0

    virtual_router_id 51

    priority 100

    advert_int 1

    authentication {

        auth_type PASS

        auth_pass 1111

    }

    virtual_ipaddress {

        192.168.229.10 #vip虛擬IP

    }

    track_script{

        check_nginx

    }

}

 

virtual_server 192.168.229.10 443 {

    delay_loop 6

    lb_algo rr

    lb_kind NAT

    persistence_timeout 50

    protocol TCP

 

    real_server 192.168.229.11 80 {

        weight 1

#心跳檢查#(HTTP_GET|SSL_GET|TCP_CHECK|SMTP_CHECK|DNS_CHECK|MISC_CHECK|BFD_CHECK)

        TCP_CHECK{

                connect_port 80

                retry 3

        }

    }

 

}

 

執行腳本:/etc/keepalived/check-nginx.sh

#!/bin/bash

 

check_nginx () {

    nginxpid=`ps -C nginx --no-header | wc -l`

    if [ $nginxpid -eq 0 ];then

        service nginx start

        sleep 1

        nginxpid=`ps -C nginx --no-header | wc -l`

        if [ $nginxpid -eq 0 ];then

            killall keepalived

        fi

    fi

}

 

check_nginx

 

! Configuration File for keepalived

 

global_defs {

   notification_email {

     acassen@firewall.loc

     failover@firewall.loc

     sysadmin@firewall.loc

   }

   notification_email_from Alexandre.Cassen@firewall.loc

   smtp_server 127.0.0.1

   smtp_connect_timeout 30

   router_id LVS_DEVEL

   vrrp_skip_check_adv_addr

   vrrp_strict

   vrrp_garp_interval 0

   vrrp_gna_interval 0

}

 

vrrp_script check_nginx{

        script "/etc/keepalived/check-nginx.sh"

        interval 2

#        timeout 1

        fall 1

}

 

vrrp_instance nginx {

    state BACKUP

    interface eth0

    virtual_router_id 51

    priority 100

    advert_int 1

    authentication {

        auth_type PASS

        auth_pass 1111

    }

    virtual_ipaddress {

        192.168.229.10

    }

    track_script{

        check_nginx

    }

}

 

virtual_server 192.168.229.10 443 {

    delay_loop 6

    lb_algo rr

    lb_kind NAT

    persistence_timeout 50

    protocol TCP

 

    real_server 192.168.229.12 80 {

        weight 1

        TCP_CHECK{

                connect_port 80

                retry 3

        }

    }

}

 

8.七、keepalived啓動

keepalived #命令直接啓動

自定義啓動腳本:autostart.sh

#!/bin/bash

#啓動後臺服務 

ssh ha3

nohup  java -jar backend.jar& #後臺服務

exit 

ssh ha4

nohup  java -jar backend.jar& #後臺服務

exit 

ssh ha5

nohup  java -jar backend.jar& #後臺服務

exit

 #啓動keepalived

ssh ha1

keepalived  

#service keepalived start

sleep 1

 ssh ha2

keepalived 

#service keepalived start

sleep 1

exit

 

九、驗證

9.一、後臺服務驗證

服務目錄:

 

index.html文件:

<!DOCTYPE html>

<html xmlns:th="http://www.thymeleaf.org">

<head>

       <title>backend</title>

       <script type="text/javascript">

              #var msg="${hostName}";

              #alert(msg);

       </script>

</head>

<body>

       <div>

              <p>templates</p>

              <p>This is backend instance!</p>

              <p th:text="${hostName}"></p>

              <p th:text="${session.hostName}"></p>

              <img src="/images/desk01.jpg" width="600" height="400"/>

              <img src="/images/desk02.jpg" width="600" height="400"/>

       </div>

</body>

</html>

application.properties配置文件

server.port=8080

spring.mvc.static-path-pattern=/**

spring.thymeleaf.cache=false

spring.thymeleaf.check-template=true

spring.thymeleaf.check-template-location=true

spring.thymeleaf.enabled=true

spring.thymeleaf.encoding=UTF-8

spring.thymeleaf.mode=HTML

spring.thymeleaf.servlet.content-type=text/html

分別在ha三、ha四、ha5啓動服務:nohup java -jar backend.jar&;注意驗證服務是否正常。

 

 

9.二、Nginx服務驗證

 

 

兩個Nginx服務正常!

9.三、Keepalived服務驗證

9.3.一、兩臺服務都正常

ha1正常:

 

ha2正常:

 

瀏覽器調用後臺服務:

 

文本瀏覽器調用後臺服務:(間隔2秒調用一次)

 

9.3.二、一臺服務都正常,一臺服務異常

 

 

 

9.四、Nginx+Keepalived服務驗證

每間隔2秒關閉一臺Nginx服務:

[root@ha1 ~]# watch -n 2 killall nginx

 

經過!!!

相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息