使用Linux、Nginx和Github Actions託管部署ASP.NET Core 6.0應用

  • 2022 年 8 月 14 日
  • 筆記

使用Linux、Nginx和Github Actions託管部署ASP.NET Core 6.0應用

前言

本文主要參考微軟這篇文檔而來 Host ASP.NET Core on Linux with Nginx,並使用Github Actions做CI&CD,部署到阿里雲伺服器,所有步驟均親測可用。

你需要有

  • Linux雲伺服器(本文使用的是阿里雲Ubantu 22.04 64位)
  • SSH客戶端(我使用的XShell, 官網 可以下載免費的家庭/學校版)
  • Github帳號以及能流程訪問^

項目準備

使用VS2022新建一個空的ASP.NET Core Web API項目,框架選擇.Net 6.0。
因為需要使用Nginx,這裡就簡單配置中間件轉發下 X-Forwarded-For X-Forwarded-Proto 兩個header。

using Microsoft.AspNetCore.HttpOverrides;

...

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

app.UseAuthentication();

本地啟動一下,看到swagger頁面,沒什麼問題。程式碼提交Github,接下來開始配置伺服器.

伺服器配置

所有包均使用 apt 命令進行安裝,如果安裝過程提示 Unable to locate package 錯誤,請先執行如下命令後,再重新安裝。

sudo apt update

安裝ASP.Net Core運行時

由於我們是部署應用,只需在伺服器上安裝運行時即可,無需安裝.net sdk

sudo apt install -y aspnetcore-runtime-6.0

查看是否安裝成功:

dotnet --info

安裝配置 Nginx

安裝Nginx

sudo apt install nginx

編輯Nginx配置文件

vim /etc/nginx/sites-available/default

Esc進入命令模式,gg跳至首行,然後dG,清空當前配置,複製粘貼下面的配置。

server {
    listen        80;
    server_name   example.com *.example.com;
    location / {
        proxy_pass         //127.0.0.1:5000;
        proxy_http_version 1.1;
        proxy_set_header   Upgrade $http_upgrade;
        proxy_set_header   Connection keep-alive;
        proxy_set_header   Host $host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto $scheme;
    }
}

退出並且保存 (Esc + :wq ,然後回車)
測試配置是否正確:

sudo nginx -t

沒問題之後,讓Nginx重新載入配置

sudo nginx -s reload

用戶及許可權

創建一個帳號等下給Github Actions使用,總不能給它用root帳號

sudo adduser github

創建一個文件夾,後面發布後的文件就上傳到這裡

sudo mkdir -p /home/project/example

給新帳號添加該文件夾的讀寫許可權

sudo chown -R github /home/project/example

到這裡其實可以手動上傳發布文件到伺服器測試一下,但是為了省時間還是跳過,直接用Github Actions來發布。

Github Actions 配置

打開Github倉庫,選擇如下官方提供的.NET工作流進入編輯頁面
image

使用如下配置:

name: ASP.NET Core 6.0 Example build and deploy
  
on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

jobs:

  build:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    - name: Setup .NET
      uses: actions/setup-dotnet@v2
      with:
        dotnet-version: 6.0.x
        
    - name: Restore dependencies
      run: dotnet restore
      
    - name: Build package
      run: dotnet publish ./src/example -c Release -r linux-x64 --self-contained false -o deploy
      
    - name: Upload package
      uses: garygrossgarten/[email protected]
      with:
        host: ${{ secrets.REMOTE_HOST }}
        username: ${{ secrets.REMOTE_USER }}
        password: ${{ secrets.REMOTE_PWD }}
        port: 22
        local: /home/runner/work/playground/example/deploy/
        remote: "/home/project/example/"

幾個需要說明的地方,

  • 關於打包,這裡指定了 --self-contained false,是為了減少發布的dll文件,更多publish命令,可以參考 .NET application publishing overview
  • 你可能已經注意到yml文件有很多secrets參數,這是在倉庫如下處進行配置
    image
  • REMOTE_HOST是伺服器地址,REMOTE_USER就是上面創建新帳號github,我這裡使用的是 garygrossgarten/github-action-scp SSH上傳文件到伺服器,更多用法說明,直接參考文檔。
    提交yml文件,打開Actions,查看執行情況,可以看到已經完成了
    image

檢查下伺服器是不是已經有發布文件了

cd /home/project/example
ls -l

image

手動運行一下,

dotnet example.dll

可以看到,外網已經可以訪問了
image

如果不能訪問,在阿里雲控制台檢查安全組規則,是否添加了80埠。
image

如果還是不能訪問,檢查一下伺服器的防火牆,將80埠添加進去。

ufw status
ufw allow 80

systemd 守護進程

為了讓服務在崩潰或者伺服器重啟之後,也能重新運行,這裡使用systemd來管理我們的服務。
創建服務定義文件:

sudo nano /etc/systemd/system/dotnet-example.service

使用如下配置,Ctrl + X 退出保存。

[Service]
WorkingDirectory=/home/project/example
ExecStart=/usr/bin/dotnet /home/project/example/example.dll
Restart=always
# Restart service after 5 seconds if the dotnet service crashes:
RestartSec=5
KillSignal=SIGINT
SyslogIdentifier=dotnet-example
User=root
Environment=ASPNETCORE_ENVIRONMENT=Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false
[Install]
WantedBy=multi-user.target

服務啟用、啟動、查看狀態:

sudo systemctl enable dotnet-example.service
sudo systemctl start dotnet-example.service
sudo systemctl status dotnet-example.service

image

最後更新Github Actions,將如下配置添加到末尾,這裡使用的是同一個人的另一個項目來執行遠程命令 garygrossgarten/github-action-ssh

    - name: Restart dotnet-example.service
      uses: garygrossgarten/[email protected]
      with:
        command: sudo systemctl restart dotnet-example.service; cd /home/project/example; ls -l
        host: ${{ secrets.REMOTE_HOST }}
        username: ${{ secrets.REMOTE_USER }}
        password: ${{ secrets.REMOTE_PWD }}

配置生效,發布成功:
image

總結

本文完整介紹了如何使用Github Actions做CI&CD,將ASP.NET Core 6.0 程式部署到阿里雲Ubantu伺服器,並使用Nginx作為web伺服器,systemd做守護進程。雖然現在k8s已經很普及,並且很多公司都基本有專門DevOps團隊維護CI&CD,程式設計師只需專註業務程式碼開發。但是了解並實操一遍整個過程還是很有益處的,特別是對新手。很多未知的坑,實踐之前你永遠不知道。就像以前也不知道寫部落格還挺累。
感嘆一下,免費的Github Actions太良心了,很方便個人項目或者私活,你完全可以只準備應用伺服器。