1. 程式人生 > 程式設計 >.Net Core + Nginx實現專案負載均衡的全步驟

.Net Core + Nginx實現專案負載均衡的全步驟

nginx大家如果沒用過那或多或少都應該聽過,vue的部署、反向代理、負載均衡nginx都能幫你做到。

今天主要說一下nginx負載均衡我們的專案,如下圖所示,請求到達nginx,nginx再幫我們轉發。

.Net Core + Nginx實現專案負載均衡的全步驟

首先使用Docker安裝nginx.

docker pull nginx:latest

執行容器,將本地的8080埠對映到容器內部的 80 埠.

docker run --name nginx -p 8080:80 -d nginx

檢視nginx容器,如果有錯請看日誌.

.Net Core + Nginx實現專案負載均衡的全步驟

瀏覽器中訪問一下

.Net Core + Nginx實現專案負載均衡的全步驟

ok,到此我們的nginx就已安裝完成。

我們準備好3個以上的webapi的專案併發布。

.Net Core + Nginx實現專案負載均衡的全步驟

進入nginx容器

Docker exec -it nginx bash

找到nginx.conf檔案並作修改,nginx.conf分為http塊、events塊和server塊,此次主要在server塊中做更改.

.Net Core + Nginx實現專案負載均衡的全步驟

此時在nginx容器裡面使用vi或者vim沒有用,需要依次執行如下兩條命令

apt-get update 
apt-get install vim

進入檔案內,末尾處指向了另一個檔案,沒錯這個檔案裡就是放server塊配置內容

.Net Core + Nginx實現專案負載均衡的全步驟

進入etc/nginx/conf.d/default.conf檔案中並做修改

.Net Core + Nginx實現專案負載均衡的全步驟

.Net Core + Nginx實現專案負載均衡的全步驟

upstream ServiceInstance{   #nginx預設輪詢下面的服務例項
  server ***.**.***.***:9007; 
  server ***.**.***.***:9008; 
  server ***.**.***.***:9009;
} 
server { 
  listen    80; 
  server_name localhost; 
 
  #charset koi8-r; 
  #access_log /var/log/nginx/host.access.log main; 
 
  location / { 
    #root  /usr/share/nginx/html; 
    #index index.html index.htm;     #請求到達後會進行轉發
    proxy_pass http://ServiceInstance; 
  } 
 
  #error_page 404       /404.html; 
 
  # redirect server error pages to the static page /50x.html 
  # 
  error_page  500 502 503 504 /50x.html; 
  location = /50x.html { 
    root  /usr/share/nginx/html; 
  } 
 
  # proxy the PHP scripts to Apache listening on 127.0.0.1:80 
  # 
  #location ~ \.php$ { 
  #  proxy_pass  http://127.0.0.1; 
  #} 
 
  # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 
  # 
  #location ~ \.php$ { 
  #  root      html; 
  #  fastcgi_pass  127.0.0.1:9000; 
  #  fastcgi_index index.php; 
  #  fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; 
  #  include    fastcgi_params; 
  #} 
 
  # deny access to .htaccess files,if Apache's document root 
  # concurs with nginx's one 
  # 
  #location ~ /\.ht { 
  #  deny all; 
  #} 
}

完成之後重啟一下容器,如果有錯誤請檢視日誌.

docker restart nginx

瀏覽器中呼叫一個介面檢視

.Net Core + Nginx實現專案負載均衡的全步驟

每一次都會輪詢不同的服務例項,負載均衡的預期就實現了!

我們也可以設定權重比例,weight值越大,請求到達此例項的次數就越多!

upstream ServiceInstance{ 
  #nginx預設輪詢下面的服務例項
  server ***.**.***.***:9007 weight=1; 
  server ***.**.***.***:9008 weight=2; 
  server ***.**.***.***:9009 weight=3;
}

各位同學也可慢慢研究,nginx很強大的!😎

到此這篇關於.Net Core + Nginx實現專案負載均衡的全步驟的文章就介紹到這了,更多相關.Net Core+Nginx專案負載均衡內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!