天天看點

nginx使用之反向代理、負載均衡

1.介紹

​ Nginx* (engine x) 是一個高性能的HTTP和反向代理web伺服器,同時也提供了電子郵件IMAP/POP3/SMTP服務代理伺服器。Nginx是由伊戈爾·賽索耶夫為俄羅斯通路量第二的Rambler.ru站點(俄文:Рамблер)開發的,

Nginx:nginx.org 是開源社群,管理着Nginx開源版。

Nginx Plus:nginx.com 是商業社群,管理着Nginx Plus商業版。

  • 俄國人開發的,開發語言Nginx代碼完全用C語言從頭寫成,是以要安裝gcc環境
  • 截止2022年7月最新主線版本1.23.0,文檔:有英語版和俄文版http://nginx.org/en/docs/
  • 具備功能:
    • 反向代理、負載均衡、限速、會話持久性
    • 負載均衡算法包括:輪詢、根據客戶ip(會話持久性),hash、權重、連接配接少的server、響應時間
  • 商業版具備功能:
    • http負載均衡:主動健康檢查/tcp和udp和gRPC主動健康檢查、連接配接數限制、流量限制等等。

說明:

本文檔的很多截圖是以nginx/1.20.1版本,yum方式安裝的,其它版本可能有些字段小差別,但是原理是一樣的。

nginx變量或指令的文檔:https://nginx.org/en/docs/http/ngx_http_core_module.html#var_remote_addr 變量都是來自對應的子產品,有這個子產品才有這個變量 。

2.Nginx的Master-Worker模式

nginx使用之反向代理、負載均衡
  • Master程序的作用是?

​ 讀取并驗證配置檔案nginx.conf;管理worker程序;

  • Worker程序的作用是?

​ worker才是處理請求的真正程序,每一個Worker程序都維護一個線程(避免線程切換),處理連接配接和請求;注意Worker程序的個數由配置檔案決定,一般和CPU個數相關(有利于程序切換),配置幾個就有幾個Worker程序。

3.Nginx如何做到熱部署?

​ 所謂熱部署,就是配置檔案nginx.conf修改後,不需要stop Nginx,不需要中斷請求,就能讓配置檔案生效!(nginx -s reload 重新加載,nginx -t檢查配置,nginx -s stop)

​ 通過上文我們已經知道worker程序負責處理具體的請求,那麼如果想達到熱部署的效果,可以想象:

方案一:

​ 修改配置檔案nginx.conf後,主程序master負責推送給woker程序更新配置資訊,woker程序收到資訊後,更新程序内部的線程資訊。(有點valatile的味道)

方案二:

​ 修改配置檔案nginx.conf後,重新生成新的worker程序,當然會以新的配置進行處理請求,而且新的請求必須都交給新的worker程序,至于老的worker程序,等把那些以前的請求處理完畢後,kill掉即可。

Nginx采用的就是方案二來達到熱部署的!

4.下載下傳和安裝

http://nginx.org/en/download.html 官網下載下傳位址

4.1yum方式安裝

  • yum install -y nginx #在epel倉庫
  • yum install -y nginx-all-modules.noarch #安裝nginx的stream子產品
  • /usr/share/nginx/html 是安裝後項目檔案夾目錄位置,index.html位置。
  • /var/log/nginx/ yum方式安裝後日志目錄
[root@dev yum.repos.d]# cat CentOS-Base.repo 
[base]
name=CentOS-$releasever - Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
baseurl=http://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/os/$basearch/
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

#released updates
[updates]
name=CentOS-$releasever - Updates
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra
baseurl=http://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/updates/$basearch/
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra
baseurl=http://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/extras/$basearch/
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra
baseurl=http://mirrors.tuna.tsinghua.edu.cn/centos/$releasever/centosplus/$basearch/
gpgcheck=0
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

[epel]
name=Extra Packages for Enterprise Linux 7 - $basearch
baseurl=https://mirrors.tuna.tsinghua.edu.cn/epel/7/$basearch
#mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-7&arch=$basearch
failovermethod=priority
enabled=1
gpgcheck=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-7
           

4.2tar包編譯安裝

官方文檔

http://nginx.org/en/docs/

5.目錄結構

5.1 yum安裝的方式

tar包安裝大同小異

[root@dev ~]# tree /etc/nginx/   
/etc/nginx/
├── conf.d #配置檔案檔案夾,也會加載這裡的
├── default.d
├── fastcgi.conf
├── fastcgi.conf.default
├── fastcgi_params
├── fastcgi_params.default
├── koi-utf
├── koi-win
├── mime.types
├── mime.types.default
├── nginx.conf #Nginx的核心配置檔案
├── nginx.conf.default #預設檔案示例,可以到這裡看一些示例
├── scgi_params
├── scgi_params.default
├── uwsgi_params
├── uwsgi_params.default
└── win-utf
           

6.日志

  • yum方式安裝
    • 預設在/var/log/nginx/目錄,error.log是錯誤日志,access.log是通路日志。
  • tar包安裝
    • 安裝目錄下的logs目錄

配置日志

​ 官方文檔:https://docs.nginx.com/nginx/admin-guide/monitoring/logging/ 文檔中有許多配置案例

  • 錯誤日志

​ error_log指令設定對特定檔案的日志記錄,錯誤日志的預設設定适用于全局。該error_log指令也可以在http、streamserver和location級别指定,并覆寫從更進階别繼承的設定。發生錯誤時,消息僅寫入一個錯誤日志,即最接近發生錯誤的級别的日志。但是,如果error_log在同一級别上指定了多個指令,則消息将寫入所有指定的日志(這個和其它應用有點不一樣)。

  • 通路日志
    • NGINX 在處理請求後立即将有關用戶端請求的資訊寫入通路日志。預設情況下,通路日志位于logs/access.log ,資訊以預定義的****組合格式寫入日志。要覆寫預設設定,請使用log_format指令更改記錄消息的格式,以及使用access_log指令指定日志的位置及其格式。日志格式是使用變量定義的。

7.Nginx指令

  • 指令方式

nginx -t #檢查配置檔案

nginx -s reload #重新加載

nginx -s stop #停止 ,-s表示signal

nginx -s quit #退出

nginx -v #檢視版本

./nginx #啟動nginx

  • 服務操作方式

systemctl start nginx #啟動nginx

systemctl status|stop|reload nginx

8.nginx.conf預設檔案示例

下面檔案是使用yum安裝後的示例,1.20版本:

  • /usr/share/nginx/html 是預設首頁目錄
  • 語句都使用分号;結束
  • events塊 – General connection processing

    http塊 – HTTP traffic

    mail塊 – Mail traffic

    stream塊 – TCP and UDP traffic

    server塊 - 表示虛拟伺服器

    location塊 - 通路的位置或通路路徑

  • 塊有子塊、父塊,子塊預設繼承了父級包含的指令的設定;當一些指令可以出現在多個塊上下文中,在這種情況下,您可以通過将指令包含在子上下文中來覆寫從父級繼承的設定。
nginx使用之反向代理、負載均衡
[root@dev yum.repos.d]# cat /etc/nginx/nginx.conf
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx; #使用什麼使用者啟動nginx
worker_processes auto; #worker數量,預設是根據cpu個數來。設定為2,work程序數是2,master數量是1.
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 4096;

    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;
        listen       [::]:80;
        server_name  _;
        root         /usr/share/nginx/html;

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

        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;
#        listen       [::]:443 ssl http2;
#        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;
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }

}
           

9. Nginx-應用

9.1 配置檔案結構

nginx的配置檔案(conf/nginx.conf)整體上分為三部分: 全局塊、events塊、http塊。這三塊的分别配置什麼樣的資訊呢,看下表:

區域 職責
全局塊 配置和nginx運作相關的全局配置,比如使用啟動的使用者、work數量、錯誤日志、程序id。
events塊 配置和網絡連接配接相關的配置。
http塊 處理http轉發,配置代理、緩存、日志記錄、虛拟主機等配置,(在http塊中可以包含多個server塊,每個server塊可以配置多個location塊)。
stream塊 主要處理tcp/udp端口負載均衡或轉發的時候,和http塊平級的,它底下可以有server。
nginx使用之反向代理、負載均衡
nginx使用之反向代理、負載均衡
nginx使用之反向代理、負載均衡

9.2 部署靜态資源

​ 其實安裝好nginx,預設就使用80端口,此時就可以打開頁面了,配置檔案不要動。

  • Nginx可以作為靜态web伺服器來部署靜态資源。這裡所說的靜态資源是指在服務端真實存在,并且能夠直接展示的一些檔案,比如常見的html頁面、css檔案、js檔案、圖檔、視訊等資源。
  • 相對于Tomcat,Nginx處理靜态資源的能力更加高效,是以在生産環境下,一般都會将靜态資源部署到Nginx中。
  • 将靜态資源部署到Nginx非常簡單,隻需要将檔案複制到Nginx安裝目錄下的html目錄中即可。
server {
     listen 80;                #監聽端口    
     server_name localhost;    #伺服器名稱
    location / {            #比對用戶端請求url
         root html;            #指定靜态資源根目錄
        index index.html;    #指定預設首頁
    }
 }
           

修改預設首頁index.html

[root@dev html]#cd /usr/share/nginx/html/
 [root@dev html]#echo "hello nginx." >> hello.html
 [root@dev html]#vi /etc/nginx/nginx.conf
 [root@dev html]#nginx -t
 [root@dev html]#systemctl reload nginx
 
[root@dev html]#less /etc/nginx/nginx.conf
server {
        listen       80;
        listen       [::]:80;
        server_name  localhost;
        root         /usr/share/nginx/html;
        #如果沒有這個location,可以自己加
        location / {
            root html;
            index hello.html;
        }

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

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

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
           
nginx使用之反向代理、負載均衡

9.3 反向代理

  • 案例1:單台轉發

使用者---->nginx伺服器:192.168.68.91---->gitlab伺服器:http://192.168.68.92:8001/

通過通路nginx伺服器80端口,要能通路到gitlab伺服器。

步驟:

  1. nginx.conf配置檔案修改。
  2. 重新加載配置。
  3. 測試,并且看日志。
  • nginx.conf配置檔案
[root@dev html]# nginx -v
nginx version: nginx/1.20.1

[root@dev html]# cat /etc/nginx/nginx.conf
# 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 3;
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 4096;

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

    include /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        listen       [::]:80;
        server_name  localhost;
        root         /usr/share/nginx/html;
        #就配置這個location而已
        location / {
            proxy_pass http://192.168.68.92:8001/;
        }

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

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

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
}
           
  • 從網頁登入的時候看日志:看到使用者有登入進來

nginx日志:tailf /var/log/nginx/access.log

  • gitlab日志:看到通路進來的位址是nginx的,沒有使用者位址表示正常。

tailf /var/log/gitlab/nginx/gitlab_access.log

# 四層負載均衡,為兩台harbor提供負載均衡
stream {
    log_format  main  '$remote_addr $upstream_addr - [$time_local] $status $upstream_bytes_sent';
    access_log  /var/log/nginx/harbor-access.log  main;
    upstream harbor{
       server 192.168.2.107:8021;   # harbor1
       server 192.168.2.108:8021;   # harbor2
    }
    server {
       listen  8121;  #由于nginx與harbor節點複用,這個監聽端口不能是8021,否則會沖突
       proxy_pass harbor;
    }
}
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;
    server {
        listen       80 default_server;
        server_name  _;
        location / {
        }
    }
}
           

9.4 負載均衡

官方文檔:

https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/

案例1:http協定負載均衡

  • 檢視http協定負載均衡支援哪些算法,官方文檔:https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/

使用者登入---->nginx伺服器(http://192.168.68.91:8090/)----->httpd伺服器(2台:192.168.68.94:8000 192.168.68.96:8000)

代理轉發的同時,還可以做負載均衡

步驟:

  1. nginx.conf配置檔案修改,(要安裝upstream子產品前面我們安裝過了就不安裝了,這裡直接修改檔案)。
  2. 重新加載配置。
  3. 測試,并且看日志。
[root@dev html]# nginx -v
nginx version: nginx/1.20.1
[root@dev html]# 
[root@dev html]# cat /etc/nginx/nginx.conf
# 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 3;
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 4096;

    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;
    
    #upstream組不加http,加到調用的server裡面。
    upstream targetvm {
        server 192.168.68.94:8000;
        server 192.168.68.96:8000;
    }

#這個server前面一個實驗配置的,不動他,新增另一個server不同端口。如果要使用這個server修改location和端口就行。
    server {
        listen       80;
        listen       [::]:80;
        server_name  localhost;
        root         /usr/share/nginx/html;
        location / {
            proxy_pass http://192.168.68.92:8001/;
        }

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

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

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

#新增一個負載均衡server,可以有多個server的,端口不一樣。
    server {
        listen       8090;
        listen       [::]:8090;
        server_name  localhost;
        location / {
            proxy_pass http://targetvm; #轉發到targetvm組中的機器,前面加http,不是https。
        }
    }

}

[root@dev html]# nginx -t #檢測檔案
[root@dev html]# nginx -s reload 
           
  • 測試

用戶端登入nginx伺服器:http://192.168.68.91:8090/ ,重新整理一次會輪訓到不同後端,在後端看日志也可以看到是nginx伺服器通路進來,不是用戶端ip,表示正常。

案例2:tcp/udp端口負載均衡

  • tcp端口福州,在配置檔案,是在頂層寫了一個stream塊,server代碼寫在他的下面。

參考資料:

檢視tcp負載均衡支援哪些算法,位址官方:https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/

部落格:https://developer.aliyun.com/article/937413

步驟:

  1. 配置nginx.conf檔案,重新加載配置。
events {
    worker_connections 1024;
}

stream {
    log_format  main  '$remote_addr $upstream_addr - [$time_local] $status $upstream_bytes_sent';
    access_log  /var/log/nginx/harbor-access.log  main;
    upstream harbor{
       server 192.168.68.94:443;   # harbor1
       server 192.168.68.96:443 backup;   # harbor2。加上backup表示,是備用,等上面機器挂了後才會使用這台機器。
    }
    server {
       listen  8121;  #由于nginx與harbor節點複用,這個監聽端口不能是8021,否則會沖突
       proxy_pass harbor;
    }
}
           

完整配置檔案示例

[root@dev html]# cat /etc/nginx/nginx.conf
# 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 3;
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;
}

stream {
    log_format  main  '$remote_addr $upstream_addr - [$time_local] $status $upstream_bytes_sent';
    access_log  /var/log/nginx/harbor-access.log  main;
    upstream harbor{
       server 192.168.68.94:443;   # harbor1
       server 192.168.68.96:443 backup;   # harbor2
    }
    server {
       listen  8121;  #由于nginx與harbor節點複用,這個監聽端口不能是8021,否則會沖突。浏覽器通路這個端口
       proxy_pass harbor;
    }
}

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 4096;

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

    server {
        listen       80;
        listen       [::]:80;
        server_name  localhost;
        root         /usr/share/nginx/html;
        location / {
        }

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

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

        error_page 500 502 503 504 /50x.html;
        location = /50x.html {
        }
    }
}
           
  • 上面配置 backup(備用)的原因,主要就是因為 Harbor 需要使用賬号密碼來進行驗證。

​ 也就是說,當我們登入到其中一台 Harbor 主機上,可能還會輪詢到另一台 Harbor 主機上,但是這另一台 Harbor主機并沒有使用賬号密碼來進行驗證。可能就會階段性的出現 401 Unauthorized(認證失敗)錯誤碼。

當然你也可以使用另外一種方法:根據源 IP 位址來決定通路哪台伺服器,加個參數hash $remote_addr consistent,也叫哈希- NGINX 根據使用者定義的密鑰選擇伺服器

upstream harbor {
       hash $remote_addr consistent; #加
       server 192.168.68.94:443;   # harbor1
       server 192.168.68.96:443;   # harbor2
    }
           

Hash

負載平衡方法也用于配置會話持久性。由于散列函數基于用戶端 IP 位址,是以來自給定用戶端的連接配接始終傳遞到同一伺服器,除非伺服器關閉或不可用。指定一個可選

consistent

參數以應用ketama一緻散列方法:

案例3:主備方式負載

下例展示了如何将 HTTP 請求代理到backend伺服器組。該組由三台伺服器組成,其中兩台運作同一應用程式的執行個體,而第三台是備份伺服器(在前面2台無法使用的情況下,會被标記為不活躍,此時backup伺服器才會生效)。因為塊中沒有指定負載平衡算法,NGINX 使用預設算法,循環,預設循環是不需要指令特别說明的。

http {
    upstream backend {
        server backend1.example.com;
        server backend2.example.com;
        server 192.0.0.1 backup; #這個關鍵字起效果
    }
    
    server {
        location / {
            proxy_pass http://backend;
        }
    }
}
           

http負載均衡算法

文檔:https://docs.nginx.com/nginx/admin-guide/load-balancer/http-load-balancer/ 這裡我不寫案例了,自己去看上面文檔,有完整的例子。

NGINX Open Source 支援四種負載均衡方法,NGINX Plus 增加了兩種方法:

  1. Round Robin輪詢預設,輪詢的時候預設也支援權重,weight參數指定,預設是1
    • upstream backend {
          server backend1.example.com weight=5;
          server backend2.example.com; #沒配置權重預設是1
          server 192.0.0.1 backup;
      }
      
      #在示例中,backend1.example.com具有 weight 5;其他兩台伺服器具有預設權重1,但帶有 IP 位址的伺服器192.0.0.1被标記為backup伺服器,除非其他兩台伺服器都不可用,否則不會接收請求。使用這種權重配置,每6個請求都會5個發送到backend1.example.com,和1個發送到backend2.example.com。
                 
  2. Least Connections – 向具有最少活動連接配接數的伺服器發送請求。
  3. IP Hash – 請求發送到的伺服器由用戶端 IP 位址确定。
  4. 通用哈希– 請求發送到的伺服器由使用者定義的鍵确定,該鍵可以是文本字元串、變量或組合。例如,密鑰可能是配對的源 IP 位址和端口,或者是本例中的 URI
  5. 最少時間(僅限 NGINX Plus,nginx商業版才有功能)
  6. 随機- 每個請求将被傳遞到随機選擇的伺服器。如果two指定了參數,首先 NGINX 會根據伺服器權重随機選擇兩台伺服器,然後使用指定的方法選擇其中一台伺服器(nginx商業版才有)

其它功能:

  • 伺服器慢啟動(商業版功能)
  • 啟用會話持久性(商業版功能)。NGINX Plus 識别使用者會話并将給定會話中的所有請求路由到同一上遊伺服器。這個和上面算法IP Hash有的不一樣,具體看官網解析。
  • 限制連接配接數(商業版功能)。有人說開源版自己安裝子產品也可以實作,後面再百度下。
  • 使用 DNS 配置 HTTP 負載平衡、Microsoft Exchange 伺服器的負載平衡(商業版功能)
  • 使用 NGINX Plus API 進行動态配置(商業版功能)

tcp/udp負載均衡算法

  • 前面4種算法和http的一樣
  • 主動 健康檢查是商業版具備功能。
  • 其它自己看文檔:https://docs.nginx.com/nginx/admin-guide/load-balancer/tcp-udp-load-balancer/

nginx配置檔案同步

商業版帶的功能,開源版沒有,得自己想辦法。

10.nginx高可用方案

答案:Keepalived+Nginx實作高可用。

​ Keepalived是一個高可用解決方案,主要是用來防止伺服器單點發生故障,可以通過和Nginx配合來實作Web服務的高可用。(其實,Keepalived不僅僅可以和Nginx配合,還可以和很多其他服務配合)

Keepalived+Nginx實作高可用的思路:

第一:請求不要直接打到Nginx上,應該先通過Keepalived(這就是所謂虛拟IP,VIP)

第二:Keepalived應該能監控Nginx的生命狀态(提供一個使用者自定義的腳本,定期檢查Nginx程序狀态,進行權重變化,,進而實作Nginx故障切換)

nginx使用之反向代理、負載均衡

問題彙總

unexpected "}" in /etc/nginx/nginx.conf

答:location 塊下的語句要用分号結尾。

繼續閱讀