1. 程式人生 > WINDOWS開發 >nginx在windows下配置負載均衡

nginx在windows下配置負載均衡

首先準備nginx的安裝包。

nginx下載地址:http://nginx.org/en/download.html

當前最新穩定版本是nginx-1.18.0

技術分享圖片

第二步修改 nginx配置檔案。

解壓nginx下載包,進入nginx解壓包的conf 資料夾,修改nginx.conf檔案.

比如nginx的根資料夾為 E:\nginx-1.18.0 ,那麼修改E:\nginx-1.18.0\conf\nginx.conf 檔案

預設配置如下:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application
/octet-stream; sendfile on; keepalive_timeout 65; server { listen 820; server_name localhost; location / { root html; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }

在上面的預設配置中,修改兩個地方:

1. 新增upstream配置節點,節點名稱為webapi2

webapi2節點裡配置三個站點url,分別為 localhost:801,localhost:802,localhost:803

2. 修改location配置節點,

刪除location節點裡的內容。

然後在location節點中新增proxy_pass節點,將proxy_pass的值指向名稱為webapi2的upstream節點。

修改後的配置如下:

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application
/octet-stream; sendfile on; keepalive_timeout 65; upstream webapi2{ server localhost:801 weight=1; server localhost:802 weight=1; server localhost:803 weight=1; } server { listen 820; server_name localhost; location / { proxy_pass http://webapi2; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } }

然後進入E:\nginx-1.18.0\ 目錄,開啟cmd命令視窗,執行 nginx.exe 命令

如果80埠被佔用,啟動 nginx 會失敗,出現下面的錯誤:

nginx: [emerg] bind() to 0.0.0.0:80 failed (10013: An attempt was made to access a socket in a way forbidden by its access permissions)

技術分享圖片

upstream節點裡的 weight 引數表示權重,數值越大表示權重越高。

這個時候修改一下監聽埠,將server 節點裡的 listen修改為別的埠試試,比如修改成820然後再次啟動nginx

    server {
        listen       820;
        server_name  localhost;

        location / {
            proxy_pass http://webapi2;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

然後再次啟動nginx,

在cmd命令列視窗中輸入nginx.exe 回車

如果啟動成功,會出現下面的效果,沒有任何提示,

技術分享圖片

為了確保nginx是否已經成功啟動,可以檢視工作管理員是否有nginx程序。

技術分享圖片

然後在瀏覽器位址列輸入 http://localhost:820/ 驗證是否可以開啟網站。