Nginx+keepalived負載均衡


 

1、安裝Nginx

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

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

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

 

擴展①:

yum install -y lsof

lsof -i:80 #在nginx啟動前,需要先檢查端口是否被占用

 

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

elinks  http://192.168.229.10 -dump

 

安裝killall命令

yum search killall

yum -y install psmisc

 

2、虛擬主機

2.1、基於IP的虛擬主機

2.2、基於端口的虛擬主機

2.3、基於域名的虛擬主機

vim /etc/hosts

 

 驗證:

 

3、長連接

# 關閉長連接:0代表關閉

keepalive_timeout 0;

# 開啟長連接(默認開啟)

# keepalive_timeout 65;

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

# keepalive_requests 8192;

 

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

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

 

5、客戶端緩存優化

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

默認值:expires off

作用域:http,server,locatio

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

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

       expires 1h;

}

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

①ctrl+f5:

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

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

優先從本地找,然后去找服務器核對信息是否一致。從本地拿數據。

③回車:

從本地緩存拿數據。

6、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;

}

 

7、Nginx基於請求頭的分發

7.1、基於host分發

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

7.2、基於開發語言分發

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

7.3、基於瀏覽器的分發

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

7.4、基於源IP分發

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

7.4.1、geo模塊

Nginx的geo模塊不僅可以有限速白名單的作用,還可以做全局負載均衡,可以要根據客戶端ip訪問到不同的server。

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

ngx_http_geo_module模塊可以用來創建變量,其值依賴於客戶端IP地址。

7.4.2、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;

    }

}

 

8、keepalived+nginx 高可用集群

8.1、架構圖

 

 

8.2、修改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.3、服務器免密碼登錄

ssh-keygen -t rsa  #一直Enter

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

 

8.4、Keepalived介紹

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

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

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

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

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

8.5、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.6、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.7、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、驗證

9.1、后台服務驗證

服務目錄:

 

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

分別在ha3、ha4、ha5啟動服務:nohup java -jar backend.jar&;注意驗證服務是否正常。

 

 

9.2、Nginx服務驗證

 

 

兩個Nginx服務正常!

9.3、Keepalived服務驗證

9.3.1、兩台服務都正常

ha1正常:

 

ha2正常:

 

瀏覽器調用后台服務:

 

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

 

9.3.2、一台服務都正常,一台服務異常

 

 

 

9.4、Nginx+Keepalived服務驗證

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

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

 

通過!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM