【.Net Core】 使用 Nginx 發布 .Net Core 3.1 項目至LInux(Centos7)。

前置部落格(部落格中使用的項目來自於此):

【Docker】 .Net Core 3.1 webapi 集成EF Code First,使用MySql進行業務操作 、配置swagger (三)

 

環境:.Net Core 3.1 , Centos7.6

工具:連接工具MobaXterm,阿里雲伺服器一台

 

1.安裝微軟簽名,不安裝不能使用net。

rpm --import https://packages.microsoft.com/keys/microsoft.asc

 

2.安裝.net環境,也可以單獨安裝 dotnet-runtime ,但是缺少很多方便的工具包,不推薦。

yum install dotnet-sdk-3.1

 

3.先修改要發布的埠號,再右鍵項目發布,然後修改資訊,發布。

 

 

 發布完,到目標文件夾把文件拖到  /home/xxx(隨意取名)   目錄下

      

dotnet Test.dll 

使用donet XXX運行項目,Test.dll是項目名。 運行後此項目只能本機訪問,沒有任何作用

 

 

 PS.

下面使用nginx進行代理轉發請求,使外網也能訪問。

如果啟動的埠是5000,Nginx 可把5000埠映射到其他埠。

 

4.添加 Nginx 存儲庫

在某些Centos版本要添加 CentOS 7 EPEL 倉庫,實測Centos7.8不需要 :

yum install epel-release

 

5.安裝 Nginx

yum install nginx

 

6.啟動 Nginx

 systemctl enable nginx  #設置nginx為開機啟動

 systemctl start nginx  #啟動nginx服務

 // 其他

 systemctl stop nginx     #停止 nginx 服務

 systemctl restart nginx  #重啟 nginx 服務

 systemctl nginx reload   #重新載入配置文件。

 systemctl status nginx   #查看伺服器狀態

 ps -ef | grep nginx      #查看Nginx是否啟動

 

 

7.修改 Nginx 配置文件

兩種方法,第一種是把 /etc/nginx/nginx.conf 文件中直接改 server 配置資訊

第二種是把 /etc/nginx/nginx.conf 文件中server注釋掉,然後在 /etc/nginx/conf.d/ 添加一個 xxx.conf 配置文件,如下所示

 

 

  紅色畫圈部分的意思是載入這個文件夾下面的所有 .conf 配置文件

 新建一個xxx.conf配置文件

 

 

 

 

 

 netcore.conf 配置如下

server {
    listen 80;
    location / {
        proxy_pass http://localhost:8001;
        
        proxy_http_version 1.1;

        proxy_set_header Upgrade $http_upgrade;

        proxy_set_header Connection keep-alive;

        proxy_set_header Host $http_host;
 
        proxy_cache_bypass $http_upgrade;
    }
}

保存後重啟nginx

 systemctl restart nginx  #重啟 nginx 服務

或者刷新配置

sudo nginx -t    #檢查配置文件
sudo nginx -s reload    #重新載入配置文件

訪問站點80埠(80埠是默認埠自動隱藏),此埠會被nginx轉發至 8001埠

 

8.配置守護進程Supervisor

項目啟動只能前台運行,不能進行其他操作,所以要建一個守護進程,使得項目後台運行

安裝 supervisor

yum install supervisor

 檢查 /etc/supervisord.conf 配置文件,如果不為圈中程式碼,請修改為圈中程式碼。

意思是 supervisord.d 文件夾下的所有 ini 類型的文件都是配置文件

 

 

 

到/etc/supervisord.d 目錄下 新建 xxx.ini文件,文件配置內容如下 自己定義,記得一定要改運行命令和程式路徑。

[program:TestNetCore]
command=dotnet Test.dll                        #運行命令
directory=/home/dotnet/Test                    #程式路徑
environment=ASPNETCORE__ENVIRONMENT=Production #環境變數
user=root        #設置啟動進程的用戶,默認是root
stopsignal=INT   #請求停止時用來殺死程式的訊號
autostart=true   #自動啟動
autorestart=true #3秒自動重啟
startsecs=3      #自動重啟間隔
stderr_logfile=/var/log/ossoffical.err.log  #標準錯誤日誌 路徑可以自定義
stdout_logfile=/var/log/ossoffical.out.log  #標準輸出日誌  路徑可以自定義

保存配置文件,啟動守護進程,然後設置開機啟動

supervisord -c /etc/supervisord.conf  #啟動服務
supervisorctl reload #重新載入配置
systemctl enable supervisord #開機啟動

其他相關操作

supervisorctl shutdown #關閉
systemctl is-enabled supervisord #驗證是否開機啟動
systemctl status supervisord.service #執行命令,查看伺服器啟動失敗的原因

 

Tags: