ASP.NET Core 8 打包 docker image

平時我們要發佈 .NET 專案是使用 dotnet publish 指令,而要打包成 docker image 則是需要先撰寫 Dockerfile ,然後再透過 docker build 指令打包為 docker image。

在 .NET 8 之後不需要 Dockerfile ,也不需要使用 docker 指令,直接使用 dotnet publish 指令就可以將專案打包為 docker image 了!(但是還是需要安裝和啟動 docker)

執行以下指令即可將專案發佈為 x64 架構的 linux 容器:
    
dotnet publish --os linux --arch x64 /t:PublishContainer
    

預設會使用全部小寫的專案名稱為 docker image 名稱,例如 WebApplication -> webapplication
要修改 image 名稱可以在 .csproj 檔案中增加 ContainerRepository 標籤,例如改名為: my-docker-image
    
<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <ContainerRepository>my-docker-image</ContainerRepository>
    </PropertyGroup>

</Project>

    

要變更基礎的 runtime 也可以在 .csproj 檔案中使用 ContainerBaseImage 標籤修改:
    
<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <ContainerRepository>my-docker-image</ContainerRepository>
        <ContainerBaseImage>mcr.microsoft.com/dotnet/runtime:8.0</ContainerBaseImage>
    </PropertyGroup>

</Project>

    

還可以指定標籤:
    
<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <ContainerRepository>my-docker-image</ContainerRepository>
        <ContainerBaseImage>mcr.microsoft.com/dotnet/runtime:8.0</ContainerBaseImage>
        <ContainerImageTag>1.2.3-alpha2</ContainerImageTag>
    </PropertyGroup>

</Project>

    

多個標籤也不是問題(ContainerImageTags 有 s):
    
<Project Sdk="Microsoft.NET.Sdk.Web">

    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <Nullable>enable</Nullable>
        <ImplicitUsings>enable</ImplicitUsings>
        <ContainerRepository>my-docker-image</ContainerRepository>
        <ContainerBaseImage>mcr.microsoft.com/dotnet/runtime:8.0</ContainerBaseImage>
        <ContainerImageTags>1.2.3-alpha2;latest</ContainerImageTags>
    </PropertyGroup>

</Project>

    

每次都要調整 .csproj 檔案很麻煩,也可以使用參數的方式:
    
dotnet publish --os linux --arch x64 /t:PublishContainer -p ContainerRepository="my-docker-image" -p ContainerImageTag="latest"
    

要啟動 docker 容器也很簡單:
    
 docker run --name my-docker-container -d -p 8080:8080 my-docker-image
    



參考資料:
Microsoft.Learn - Containerize a .NET app with dotnet publish

留言

張貼留言

如果有任何問題、建議、想說的話或文章題目推薦,都歡迎留言或來信: a@ruyut.com