.Net Core+Nginx實現項目負載均衡

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

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

首先使用Docker安裝nginx.

docker pull nginx:latest

運行容器,將本地的8080端口映射到容器內部的 80 端口.

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

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

 瀏覽器中訪問一下

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

我們準備好3個以上的webapi的項目併發布。

進入nginx容器

Docker exec -it nginx bash

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

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

apt-get update  
apt-get install vim

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

進入etc/nginx/conf.d/default.conf文件中並做修改

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

瀏覽器中調用一個接口查看

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

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

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

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章