Nginx負載均衡配置


Nginx是一款輕量級的Web 服務器/反向代理服務器及電子郵件(IMAP/POP3)代理服務器,在BSD-like 協議下發行。其特點是占有內存少,並發能力強,事實上nginx的並發能力在同類型的網頁服務器中表現較好。

本篇文章主要介紹nginx復雜均衡配置,以及配置過程中遇到的一些問題。負載用的實例以docker為主。

v安裝nginx

yum -y install nginx

注意:若在這一步,遇到錯誤提示 沒有可用軟件包 nginx。 ,可以看看文章《yum install nginx-沒有可用軟件包 nginx。》提供了詳細的解決辦法。

安裝完畢查一下nginx版本號 nginx -v

順便通過 rpm -ql nginx 查看nginx的安裝目錄。/etc/nginx主要都是配置文件,/var/log/nginx主要都是nginx相關日志。

Nginx負載均衡配置

圖片來源於網絡,侵刪。

啟動 Nginx : systemctl start nginx

若開啟了防火牆,可以先關閉防火牆。 systemctl stop firewalld

設置nginx自動啟動: systemctl enable nginx

啟動nginx: systemctl start nginx

關閉nginx: systemctl stop nginx

重啟nginx: systemctl restart nginx

查看nginx: systemctl status nginx

查看nginx失敗原因: systemctl status nginx.service 或者 journalctl -xe 。這個很有用,在配置nginx.conf時配錯了,啟動nginx起不來,可以通過這個命令查看。

v詳解nginx.conf

其實我們常說的Nginx負載均衡配置,Nginx負載均衡配置。 一般主要就是配置nginx.conf。

2.0 nginx.conf默認配置

Nginx負載均衡配置
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

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"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;
    
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }

# Settings for a TLS enabled server.
#
#    server {
#        listen       443 ssl http2 default_server;
#        listen       [::]:443 ssl http2 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        ssl_certificate "/etc/pki/nginx/server.crt";
#        ssl_certificate_key "/etc/pki/nginx/private/server.key";
#        ssl_session_cache shared:SSL:1m;
#        ssl_session_timeout  10m;
#        ssl_ciphers HIGH:!aNULL:!MD5;
#        ssl_prefer_server_ciphers on;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#        location = /404.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#        location = /50x.html {
#        }
#    }

}
View Code

2.1 nginx.conf文件目錄

...              #全局塊

events {         #events塊
   ...
}

http      #http塊
{
    ...   #http全局塊
    server        #server塊
    { 
        ...       #server全局塊
        location [PATTERN]   #location塊
        {
            ...
        }
        location [PATTERN] 
        {
            ...
        }
    }
    server
    {
      ...
    }
    ...     #http全局塊
}

2.2 nginx.conf詳解:

######Nginx配置文件nginx.conf中文詳解#####

#定義Nginx運行的用戶和用戶組
user www www;

#nginx進程數,建議設置為等於CPU總核心數。
worker_processes 8;
 
#全局錯誤日志定義類型,[ debug | info | notice | warn | error | crit ]
error_log /usr/local/nginx/logs/error.log info;

#進程pid文件
pid /usr/local/nginx/logs/nginx.pid;

#指定進程可以打開的最大描述符:數目
#工作模式與連接數上限
#這個指令是指當一個nginx進程打開的最多文件描述符數目,理論值應該是最多打開文件數(ulimit -n)與nginx進程數相除,但是nginx分配請求並不是那么均勻,所以最好與ulimit -n 的值保持一致。
#現在在linux 2.6內核下開啟文件打開數為65535,worker_rlimit_nofile就相應應該填寫65535。
#這是因為nginx調度時分配請求到進程並不是那么的均衡,所以假如填寫10240,總並發量達到3-4萬時就有進程可能超過10240了,這時會返回502錯誤。
worker_rlimit_nofile 65535;


events
{
    #參考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型
    #是Linux 2.6以上版本內核中的高性能網絡I/O模型,linux建議epoll,如果跑在FreeBSD上面,就用kqueue模型。
    #補充說明:
    #與apache相類,nginx針對不同的操作系統,有不同的事件模型
    #A)標准事件模型
    #Select、poll屬於標准事件模型,如果當前系統不存在更有效的方法,nginx會選擇select或poll
    #B)高效事件模型
    #Kqueue:使用於FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X.使用雙處理器的MacOS X系統使用kqueue可能會造成內核崩潰。
    #Epoll:使用於Linux內核2.6版本及以后的系統。
    #/dev/poll:使用於Solaris 7 11/99+,HP/UX 11.22+ (eventport),IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。
    #Eventport:使用於Solaris 10。 為了防止出現內核崩潰的問題, 有必要安裝安全補丁。
    use epoll;

    #單個進程最大連接數(最大連接數=連接數*進程數)
    #根據硬件調整,和前面工作進程配合起來用,盡量大,但是別把cpu跑到100%就行。每個進程允許的最多連接數,理論上每台nginx服務器的最大連接數為。
    worker_connections 65535;

    #keepalive超時時間。
    keepalive_timeout 60;

    #客戶端請求頭部的緩沖區大小。這個可以根據你的系統分頁大小來設置,一般一個請求頭的大小不會超過1k,不過由於一般系統分頁都要大於1k,所以這里設置為分頁大小。
    #分頁大小可以用命令getconf PAGESIZE 取得。
    #[root@web001 ~]# getconf PAGESIZE
    #4096
    #但也有client_header_buffer_size超過4k的情況,但是client_header_buffer_size該值必須設置為“系統分頁大小”的整倍數。
    client_header_buffer_size 4k;

    #這個將為打開文件指定緩存,默認是沒有啟用的,max指定緩存數量,建議和打開文件數一致,inactive是指經過多長時間文件沒被請求后刪除緩存。
    open_file_cache max=65535 inactive=60s;

    #這個是指多長時間檢查一次緩存的有效信息。
    #語法:open_file_cache_valid time 默認值:open_file_cache_valid 60 使用字段:http, server, location 這個指令指定了何時需要檢查open_file_cache中緩存項目的有效信息.
    open_file_cache_valid 80s;

    #open_file_cache指令中的inactive參數時間內文件的最少使用次數,如果超過這個數字,文件描述符一直是在緩存中打開的,如上例,如果有一個文件在inactive時間內一次沒被使用,它將被移除。
    #語法:open_file_cache_min_uses number 默認值:open_file_cache_min_uses 1 使用字段:http, server, location  這個指令指定了在open_file_cache指令無效的參數中一定的時間范圍內可以使用的最小文件數,如果使用更大的值,文件描述符在cache中總是打開狀態.
    open_file_cache_min_uses 1;
    
    #語法:open_file_cache_errors on | off 默認值:open_file_cache_errors off 使用字段:http, server, location 這個指令指定是否在搜索一個文件是記錄cache錯誤.
    open_file_cache_errors on;
}
 
 
 
#設定http服務器,利用它的反向代理功能提供負載均衡支持
http
{
    #文件擴展名與文件類型映射表
    include mime.types;

    #默認文件類型
    default_type application/octet-stream;

    #默認編碼
    #charset utf-8;

    #服務器名字的hash表大小
    #保存服務器名字的hash表是由指令server_names_hash_max_size 和server_names_hash_bucket_size所控制的。參數hash bucket size總是等於hash表的大小,並且是一路處理器緩存大小的倍數。在減少了在內存中的存取次數后,使在處理器中加速查找hash表鍵值成為可能。如果hash bucket size等於一路處理器緩存的大小,那么在查找鍵的時候,最壞的情況下在內存中查找的次數為2。第一次是確定存儲單元的地址,第二次是在存儲單元中查找鍵 值。因此,如果Nginx給出需要增大hash max size 或 hash bucket size的提示,那么首要的是增大前一個參數的大小.
    server_names_hash_bucket_size 128;

    #客戶端請求頭部的緩沖區大小。這個可以根據你的系統分頁大小來設置,一般一個請求的頭部大小不會超過1k,不過由於一般系統分頁都要大於1k,所以這里設置為分頁大小。分頁大小可以用命令getconf PAGESIZE取得。
    client_header_buffer_size 32k;

    #客戶請求頭緩沖大小。nginx默認會用client_header_buffer_size這個buffer來讀取header值,如果header過大,它會使用large_client_header_buffers來讀取。
    large_client_header_buffers 4 64k;

    #設定通過nginx上傳文件的大小
    client_max_body_size 8m;

    #開啟高效文件傳輸模式,sendfile指令指定nginx是否調用sendfile函數來輸出文件,對於普通應用設為 on,如果用來進行下載等應用磁盤IO重負載應用,可設置為off,以平衡磁盤與網絡I/O處理速度,降低系統的負載。注意:如果圖片顯示不正常把這個改成off。
    #sendfile指令指定 nginx 是否調用sendfile 函數(zero copy 方式)來輸出文件,對於普通應用,必須設為on。如果用來進行下載等應用磁盤IO重負載應用,可設置為off,以平衡磁盤與網絡IO處理速度,降低系統uptime。
    sendfile on;

    #開啟目錄列表訪問,合適下載服務器,默認關閉。
    autoindex on;

    #此選項允許或禁止使用socke的TCP_CORK的選項,此選項僅在使用sendfile的時候使用
    tcp_nopush on;
     
    tcp_nodelay on;

    #長連接超時時間,單位是秒
    keepalive_timeout 120;

    #FastCGI相關參數是為了改善網站的性能:減少資源占用,提高訪問速度。下面參數看字面意思都能理解。
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 64k;
    fastcgi_buffers 4 64k;
    fastcgi_busy_buffers_size 128k;
    fastcgi_temp_file_write_size 128k;

    #gzip模塊設置
    gzip on; #開啟gzip壓縮輸出
    gzip_min_length 1k;    #最小壓縮文件大小
    gzip_buffers 4 16k;    #壓縮緩沖區
    gzip_http_version 1.0;    #壓縮版本(默認1.1,前端如果是squid2.5請使用1.0)
    gzip_comp_level 2;    #壓縮等級
    gzip_types text/plain application/x-javascript text/css application/xml;    #壓縮類型,默認就已經包含textml,所以下面就不用再寫了,寫上去也不會有問題,但是會有一個warn。
    gzip_vary on;

    #開啟限制IP連接數的時候需要使用
    #limit_zone crawler $binary_remote_addr 10m;



    #負載均衡配置
    upstream jh.w3cschool.cn {
     
        #upstream的負載均衡,weight是權重,可以根據機器配置定義權重。weigth參數表示權值,權值越高被分配到的幾率越大。
        server 192.168.80.121:80 weight=3;
        server 192.168.80.122:80 weight=2;
        server 192.168.80.123:80 weight=3;

        #nginx的upstream目前支持4種方式的分配
        #1、輪詢(默認)
        #每個請求按時間順序逐一分配到不同的后端服務器,如果后端服務器down掉,能自動剔除。
        #2、weight
        #指定輪詢幾率,weight和訪問比率成正比,用於后端服務器性能不均的情況。
        #例如:
        #upstream bakend {
        #    server 192.168.0.14 weight=10;
        #    server 192.168.0.15 weight=10;
        #}
        #2、ip_hash
        #每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個后端服務器,可以解決session的問題。
        #例如:
        #upstream bakend {
        #    ip_hash;
        #    server 192.168.0.14:88;
        #    server 192.168.0.15:80;
        #}
        #3、fair(第三方)
        #按后端服務器的響應時間來分配請求,響應時間短的優先分配。
        #upstream backend {
        #    server server1;
        #    server server2;
        #    fair;
        #}
        #4、url_hash(第三方)
        #按訪問url的hash結果來分配請求,使每個url定向到同一個后端服務器,后端服務器為緩存時比較有效。
        #例:在upstream中加入hash語句,server語句中不能寫入weight等其他的參數,hash_method是使用的hash算法
        #upstream backend {
        #    server squid1:3128;
        #    server squid2:3128;
        #    hash $request_uri;
        #    hash_method crc32;
        #}

        #tips:
        #upstream bakend{#定義負載均衡設備的Ip及設備狀態}{
        #    ip_hash;
        #    server 127.0.0.1:9090 down;
        #    server 127.0.0.1:8080 weight=2;
        #    server 127.0.0.1:6060;
        #    server 127.0.0.1:7070 backup;
        #}
        #在需要使用負載均衡的server中增加 proxy_pass http://bakend/;

        #每個設備的狀態設置為:
        #1.down表示單前的server暫時不參與負載
        #2.weight為weight越大,負載的權重就越大。
        #3.max_fails:允許請求失敗的次數默認為1.當超過最大次數時,返回proxy_next_upstream模塊定義的錯誤
        #4.fail_timeout:max_fails次失敗后,暫停的時間。
        #5.backup: 其它所有的非backup機器down或者忙的時候,請求backup機器。所以這台機器壓力會最輕。

        #nginx支持同時設置多組的負載均衡,用來給不用的server來使用。
        #client_body_in_file_only設置為On 可以講client post過來的數據記錄到文件中用來做debug
        #client_body_temp_path設置記錄文件的目錄 可以設置最多3層目錄
        #location對URL進行匹配.可以進行重定向或者進行新的代理 負載均衡
    }
     
     
     
    #虛擬主機的配置
    server
    {
        #監聽端口
        listen 80;

        #域名可以有多個,用空格隔開
        server_name www.w3cschool.cn w3cschool.cn;
        index index.html index.htm index.php;
        root /data/www/w3cschool;

        #對******進行負載均衡
        location ~ .*.(php|php5)?$
        {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi.conf;
        }
         
        #圖片緩存時間設置
        location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires 10d;
        }
         
        #JS和CSS緩存時間設置
        location ~ .*.(js|css)?$
        {
            expires 1h;
        }
         
        #日志格式設定
        #$remote_addr與$http_x_forwarded_for用以記錄客戶端的ip地址;
        #$remote_user:用來記錄客戶端用戶名稱;
        #$time_local: 用來記錄訪問時間與時區;
        #$request: 用來記錄請求的url與http協議;
        #$status: 用來記錄請求狀態;成功是200,
        #$body_bytes_sent :記錄發送給客戶端文件主體內容大小;
        #$http_referer:用來記錄從那個頁面鏈接訪問過來的;
        #$http_user_agent:記錄客戶瀏覽器的相關信息;
        #通常web服務器放在反向代理的后面,這樣就不能獲取到客戶的IP地址了,通過$remote_add拿到的IP地址是反向代理服務器的iP地址。反向代理服務器在轉發請求的http頭信息中,可以增加x_forwarded_for信息,用以記錄原有客戶端的IP地址和原來客戶端的請求的服務器地址。
        log_format access '$remote_addr - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" '
        '"$http_user_agent" $http_x_forwarded_for';
         
        #定義本虛擬主機的訪問日志
        access_log  /usr/local/nginx/logs/host.access.log  main;
        access_log  /usr/local/nginx/logs/host.access.404.log  log404;
         
        #對 "/" 啟用反向代理
        location / {
            proxy_pass http://127.0.0.1:88;
            proxy_redirect off;
            proxy_set_header X-Real-IP $remote_addr;
             
            #后端的Web服務器可以通過X-Forwarded-For獲取用戶真實IP
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             
            #以下是一些反向代理的配置,可選。
            proxy_set_header Host $host;

            #允許客戶端請求的最大單文件字節數
            client_max_body_size 10m;

            #緩沖區代理緩沖用戶端請求的最大字節數,
            #如果把它設置為比較大的數值,例如256k,那么,無論使用firefox還是IE瀏覽器,來提交任意小於256k的圖片,都很正常。如果注釋該指令,使用默認的client_body_buffer_size設置,也就是操作系統頁面大小的兩倍,8k或者16k,問題就出現了。
            #無論使用firefox4.0還是IE8.0,提交一個比較大,200k左右的圖片,都返回500 Internal Server Error錯誤
            client_body_buffer_size 128k;

            #表示使nginx阻止HTTP應答代碼為400或者更高的應答。
            proxy_intercept_errors on;

            #后端服務器連接的超時時間_發起握手等候響應超時時間
            #nginx跟后端服務器連接超時時間(代理連接超時)
            proxy_connect_timeout 90;

            #后端服務器數據回傳時間(代理發送超時)
            #后端服務器數據回傳時間_就是在規定時間之內后端服務器必須傳完所有的數據
            proxy_send_timeout 90;

            #連接成功后,后端服務器響應時間(代理接收超時)
            #連接成功后_等候后端服務器響應時間_其實已經進入后端的排隊之中等候處理(也可以說是后端服務器處理請求的時間)
            proxy_read_timeout 90;

            #設置代理服務器(nginx)保存用戶頭信息的緩沖區大小
            #設置從被代理服務器讀取的第一部分應答的緩沖區大小,通常情況下這部分應答中包含一個小的應答頭,默認情況下這個值的大小為指令proxy_buffers中指定的一個緩沖區的大小,不過可以將其設置為更小
            proxy_buffer_size 4k;

            #proxy_buffers緩沖區,網頁平均在32k以下的設置
            #設置用於讀取應答(來自被代理服務器)的緩沖區數目和大小,默認情況也為分頁大小,根據操作系統的不同可能是4k或者8k
            proxy_buffers 4 32k;

            #高負荷下緩沖大小(proxy_buffers*2)
            proxy_busy_buffers_size 64k;

            #設置在寫入proxy_temp_path時數據的大小,預防一個工作進程在傳遞文件時阻塞太長
            #設定緩存文件夾大小,大於這個值,將從upstream服務器傳
            proxy_temp_file_write_size 64k;
        }
         
         
        #設定查看Nginx狀態的地址
        location /NginxStatus {
            stub_status on;
            access_log on;
            auth_basic "NginxStatus";
            auth_basic_user_file confpasswd;
            #htpasswd文件的內容可以用apache提供的htpasswd工具來產生。
        }
         
        #本地動靜分離反向代理配置
        #所有jsp的頁面均交由tomcat或resin處理
        location ~ .(jsp|jspx|do)?$ {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_pass http://127.0.0.1:8080;
        }
         
        #所有靜態文件由nginx直接讀取不經過tomcat或resin
        location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|
        pdf|xls|mp3|wma)$
        {
            expires 15d; 
        }
         
        location ~ .*.(js|css)?$
        {
            expires 1h;
        }
    }
}

v配置nginx.conf

3.1 創建springboot工程,添加測試用的接口

/**
 * @author toutou
 * @date by 2020/11
 * @des
 */
@Slf4j
@RestController
public class IndexController {
    @GetMapping("/index")
    public Result index(HttpServletRequest req) {
        String ip = "";
        try {
            InetAddress localHost = InetAddress.getLocalHost();
            if (localHost != null && localHost.getHostAddress() != null) {
                String[] split = localHost.getHostAddress().split("\\.");
                if (split.length > 1) {
                    ip = split[split.length - 1];
                }
            }
        } catch (Exception ipe) {
            log.warn("Caught Exception when get ip", ipe);
        }

        String message = String.format("Server ip:%s; Server Port:%d;Local Port:%d", ip, req.getServerPort(), req.getLocalPort());
        return Result.setSuccessResult(message);
    }
}

如果不會創建springboot工程的也沒有關系,可以看看SpringBoot入門教程(一)詳解intellij idea搭建SpringBoot,手把手教程。

3.2 如下圖,先創建6個docker springboot實例

Nginx負載均衡配置

如果不會docker部署springboot的話,可以看看詳解docker部署SpringBoot及如何替換jar包,手把手教程。

3.3 設置nginx.conf配置

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

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"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;
    
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
    
    upstream hellolearn1 {
        server 127.0.0.1:8301;
        server 127.0.0.1:8302;
        server 127.0.0.1:8303;
    }
    
    server {
        listen       8080;
        server_name  www.toutou.com;

        location / {
            proxy_pass http://hellolearn1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
}

主要是在原有的nginx.conf配置文件中追加upstream塊和server塊。

客戶端host配置

ip www.toutou.com
ip www.nginxconfig.com
ip api.nginxconfig.com

3.4 測試效果

Nginx負載均衡配置

3次請求分別命中了3個docker實例,這是因為上面配置文件upstream塊中沒有配置nginx負載均衡的分配方式,默認是輪詢方式。

3.5 nginx負載分配方式:

3.5.1 輪詢

默認方式,每個請求按時間順序逐一分配到不同的后端服務器,如果后端服務器down掉,能自動剔除。雖然這種方式簡便、成本低廉。但缺點是:可靠性低和負載分配不均衡。適用於圖片服務器集群和純靜態頁面服務器集群。

3.5.2 weight(權重分配)

指定輪詢幾率,權重越高,在被訪問的概率越大,用於后端服務器性能不均的情況。

例子:

upstream hellolearn{ 
    server 127.0.0.1:8001 weight=1; 
    server 127.0.0.1:8002 weight=2; 
    server 127.0.0.1:8003 weight=3;
}

當Nginx每收到6個請求,會把其中的1個轉發給8001,把其中的2個轉發給8002,把其中的3個轉發給8003。

3.5.3 ip_hash

每個請求按訪問ip的hash結果分配,這樣每個訪客固定訪問一個后端服務器,可以解決session的問題。

例子:

upstream hellolearn{ 
    ip_hash; 
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
}

3.5.4 fair(第三方)

按后端服務器的響應時間分配,響應時間短的優先分配,依賴第三方插件 nginx-upstream-fair,需要先安裝。

例子:

upstream hellolearn{ 
    fair; 
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
}

3.5.5 url_hash(第三方)

按訪問url的hash結果來分配請求,使每個url定向到同一個后端服務器,后端服務器為緩存時比較有效。在upstream中加入hash語句,hash_method是使用的hash算法。

例子:

upstream hellolearn{ 
    server 127.0.0.1:8001;
    server 127.0.0.1:8002;
    server 127.0.0.1:8003;
    hash $request_uri; 
    hash_method crc32; 
}

nginx 1.7.2版本后,已經集成了url hash功能,可直接使用,不要安裝三方模塊。 該信息來自網絡,未親測,感興趣的朋友可以試試。

3.6 負載均衡調度中的狀態

Nginx負載均衡配置

例子:

upstream hellolearn {
    server 127.0.0.1:8301 down;
    server 127.0.0.1:8302 backup;
    server 127.0.0.1:8303 max_fails=3 fail_timeout=30s;
}

注意:若訪問nginx提示502的話,可以查看一下日志 less /var/log/nginx/error.log 。若發現提示Permission denied,輸入命令 setsebool -P httpd_can_network_connect 1 即可解決。

v進階配置

http塊中可以有多個upstream塊和server塊,那么我們就來配置多個upstream塊和server塊看看什么效果。

4.1 nginx.conf中追加upstream塊和server

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

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"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    include /etc/nginx/conf.d/*.conf;
    
    server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
        location = /404.html {
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
    
    upstream hellolearn1 {
        server 127.0.0.1:8301;
        server 127.0.0.1:8302;
        server 127.0.0.1:8303;
    }
    
    server {
        listen       8080;
        server_name  www.toutou.com;

        location / {
            proxy_pass http://hellolearn1;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }
    
    upstream hellolearn2 {
        server 127.0.0.1:8304;
        server 127.0.0.1:8305;
        server 127.0.0.1:8306;
    }
    
    server {
        listen       8090;
        server_name  www.nginxconfig.com;

        #負載到upstream hellolearn2
        location / {
            proxy_pass http://hellolearn2;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
        
        #匹配以/images/開頭的任何查詢並停止搜索,表示匹配URL時忽略字母大小寫問題
        location ^~ /sayhello/ {
            default_type 'text/plain';
            return 200 "say hello.";
        }
    }
    
    server {
        listen       8099;
        server_name  ~.*nginxconfig.com;

        #可以匹配所有請求
        location / {
            default_type "text/html;charset=utf-8";
            return 200 "<p style='color:red;'>我可以匹配所有請求</p>";
        }
        
        #只有當用戶請求是/時,才會使用該location下的配置
        location = / {
            default_type "text/html;charset=utf-8";
            return 404 "<p style='color:blue;font-weight: bold;'>只有根目錄才能發現我</p>";
        }
        
        #匹配任何以.red、.blue或者.black結尾的請求。
        location ~* \.(red|blue|black)$ {
            default_type "text/html;charset=utf-8";
            return 200 "<p>red or blue or black</p>";
        }
    }
}

4.2 運行效果圖

Nginx負載均衡配置

在nginx.conf末尾處中追加了一組upstream塊和兩組server塊,其中兩組server塊共計包含5組location,上圖中的5個演示效果,正是對應上末尾追加的5個location塊的匹配規則的。

4.3 server_name的作用

server name 為虛擬服務器的識別路徑。因此不同的域名會通過請求頭中的HOST字段,匹配到特定的server塊,轉發到對應的應用服務器中去。

server_name與Host的匹配優先級:

首先選擇所有字符串完全匹配的server_name。如:www.toutou.com

其次選擇通配符在前面的server_name。如:*.toutou.com

其次選擇通配符在后面的server_name。如:www.toutou.*

最后選擇使用正在表達式才匹配的server_name。如:~^\.toutou\.com$

如果上面這些都不匹配

1、優先選擇listen配置項后有default或default_server的

2、找到匹配listen端口的第一個server塊

4.4 location匹配規則

location后面的這些 = 或者 ~ 具體是干嘛用的呢,分別介紹一下。

語法: location [=|~|~*|^~] /uri/ { … }

4.4.1 = 精確匹配路徑,用於不含正則表達式的 uri 前,如果匹配成功,不再進行后續的查找。

4.4.2 ^~ 用於不含正則表達式的 uri; 前,表示如果該符號后面的字符是最佳匹配,采用該規則,不再進行后續的查找。

4.4.3 ~ 表示用該符號后面的正則去匹配路徑,區分大小寫。

4.4.4 ~* 表示用該符號后面的正則去匹配路徑,不區分大小寫。跟 ~ 優先級都比較低,如有多個location的正則能匹配的話,則使用正則表達式最長的那個。

v博客總結

Nginx能成為最受歡迎的web服務器之一,功能十分強大,還有很多功能值我們去學習。

其他參考/學習資料:

v源碼地址

https://github.com/toutouge/javademosecond/tree/master/hellolearn


作  者:請叫我頭頭哥
出  處:http://www.cnblogs.com/toutou/
關於作者:專注於基礎平台的項目開發。如有問題或建議,請多多賜教!
版權聲明:本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文鏈接。
特此聲明:所有評論和私信都會在第一時間回復。也歡迎園子的大大們指正錯誤,共同進步。或者直接私信
聲援博主:如果您覺得文章對您有幫助,可以點擊文章右下角推薦一下。您的鼓勵是作者堅持原創和持續寫作的最大動力!


免責聲明!

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



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