教學課程:將 Windows 容器中的 .NET 應用程式部署到 Azure Service FabricTutorial: Deploy a .NET application in a Windows container to Azure Service Fabric

本教學課程示範如何將現有的 ASP.NET 應用程式容器化,並封裝為 Service Fabric 應用程式。This tutorial shows you how to containerize an existing ASP.NET application and package it as a Service Fabric application. 在 Service Fabric 開發叢集上本機執行容器,然後將此應用程式部署到 Azure。Run the containers locally on the Service Fabric development cluster and then deploy the application to Azure. 應用程式的資料會保存在 Azure SQL Database 中。The application persists data in Azure SQL Database.

在本教學課程中,您了解如何:In this tutorial, you learn how to:

  • 使用 Visual Studio 將現有應用程式容器化Containerize an existing application using Visual Studio
  • 建立 Azure SQL 資料庫Create an Azure SQL database
  • 建立 Azure 容器登錄Create an Azure container registry
  • 將 Service Fabric 應用程式部署至 AzureDeploy a Service Fabric application to Azure

注意

本文已更新為使用新的 Azure PowerShell Az 模組。This article has been updated to use the new Azure PowerShell Az module. AzureRM 模組在至少 2020 年 12 月之前都還會持續收到錯誤 (Bug) 修正,因此您仍然可以持續使用。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要深入了解新的 Az 模組和 AzureRM 的相容性,請參閱新的 Azure PowerShell Az 模組簡介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 如需 Az 模組安裝指示,請參閱安裝 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

必要條件Prerequisites

  1. 如果您沒有 Azure 訂用帳戶,請建立免費帳戶If you don't have an Azure subscription, create a free account
  2. 安裝 Docker CE for Windows,以便在 Windows 10 上執行容器。Install Docker CE for Windows so that you can run containers on Windows 10.
  3. 安裝 Service Fabric 執行階段 6.2 版或更新版本Service Fabric SDK 3.1 版或更新版本。Install Service Fabric runtime version 6.2 or later and the Service Fabric SDK version 3.1 or later.
  4. 安裝 Visual Studio 2019 16.1 版或更新版本,其中包含 Azure 開發ASP.NET 和 Web 開發工作負載。Install Visual Studio 2019 Version 16.1 or later with the Azure development and ASP.NET and web development workloads.
  5. 安裝 Azure PowerShellInstall Azure PowerShell

下載並執行 Fabrikam Fiber CallCenterDownload and run Fabrikam Fiber CallCenter

下載 Fabrikam Fiber CallCenter 範例應用程式。Download the Fabrikam Fiber CallCenter sample application. 按一下 [下載封存] 連結。Click the download archive link. 從 fabrikam.zip 檔案中的 sourceCode 目錄 ,解壓縮 sourceCode.zip 檔案,然後將 VS2015 目錄解壓縮到電腦中。From the sourceCode directory in the fabrikam.zip file, extract the sourceCode.zip file and then extract the VS2015 directory to your computer.

確認 Fabrikam Fiber CallCenter 應用程式建置及執行正常。Verify that the Fabrikam Fiber CallCenter application builds and runs without error. 系統管理員身分啟動 Visual Studio,並開啟 FabrikamFiber.CallCenter.sln 檔案。Launch Visual Studio as an administrator and open the FabrikamFiber.CallCenter.sln file. 按 F5 進行偵錯並執行應用程式。Press F5 to debug and run the application.

Fabrikam Web 範例

將應用程式容器化Containerize the application

在 [FabrikamFiber.Web] 專案上按一下滑鼠右鍵 > [新增] > [容器協調器支援] 。Right-click the FabrikamFiber.Web project > Add > Container Orchestrator Support. 選取 [Service Fabric] 作為容器協調器,然後按一下 [確定] 。Select Service Fabric as the container orchestrator and click OK.

按一下 [是] ,可立即將 Docker 切換到 Windows 容器。Click Yes to switch Docker to Windows containers now.

現在在方案中已建立新的 Service Fabric 應用程式專案 FabrikamFiber.CallCenterApplicationA new project Service Fabric application project FabrikamFiber.CallCenterApplication is created in the solution. 並已在現有 FabrikamFiber.Web 專案中新增 Dockerfile。A Dockerfile is added to the existing FabrikamFiber.Web project. PackageRoot 目錄也已新增至 FabrikamFiber.Web 專案,其中包含新 FabrikamFiber.Web 服務的服務資訊清單和設定。A PackageRoot directory is also added to the FabrikamFiber.Web project, which contains the service manifest and settings for the new FabrikamFiber.Web service.

現在準備好在 Service Fabric 應用程式中建置及封裝此容器。The container is now ready to be built and packaged in a Service Fabric application. 在您的電腦上建置完容器映像之後,您便可以將它推送到任何容器登錄,然後下拉到任何主機來執行。Once you have the container image built on your machine, you can push it to any container registry and pull it down to any host to run.

建立 Azure SQL 資料庫Create an Azure SQL DB

在生產環境中執行 Fabrikam Fiber CallCenter 應用程式時,資料必須保存在資料庫中。When running the Fabrikam Fiber CallCenter application in production, the data needs to be persisted in a database. 目前無法保證資料能保存在容器中,因此請不要將 SQL Server 生產環境的資料儲存在容器中。There is currently no way to guarantee persistent data in a container, therefore you cannot store production data in SQL Server in a container.

建議使用 Azure SQL DatabaseWe recommend Azure SQL Database. 若要在 Azure 中設定及執行受控 SQL Server 資料庫,執行下列指令碼。To set up and run a managed SQL Server DB in Azure, run the following script. 視需要修改指令碼變數。Modify the script variables as necessary. clientIP 是開發電腦的 IP 位址。clientIP is the IP address of your development computer. 記下由指令碼輸出的伺服器名稱。Take note of the name of the server outputted by the script.

$subscriptionID="<subscription ID>"

# Sign in to your Azure account and select your subscription.
Login-AzAccount -SubscriptionId $subscriptionID 

# The data center and resource name for your resources.
$dbresourcegroupname = "fabrikam-fiber-db-group"
$location = "southcentralus"

# The logical server name: Use a random value or replace with your own value (do not capitalize).
$servername = "fab-fiber-$(Get-Random)"

# Set an admin login and password for your database.
# The login information for the server.
$adminlogin = "ServerAdmin"
$password = "Password@123"

# The IP address of your development computer that accesses the SQL DB.
$clientIP = "<client IP>"

# The database name.
$databasename = "call-center-db"

# Create a new resource group for your deployment and give it a name and a location.
New-AzResourceGroup -Name $dbresourcegroupname -Location $location

# Create the SQL server.
New-AzSqlServer -ResourceGroupName $dbresourcegroupname `
    -ServerName $servername `
    -Location $location `
    -SqlAdministratorCredentials $(New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $adminlogin, $(ConvertTo-SecureString -String $password -AsPlainText -Force))

# Create the firewall rule to allow your development computer to access the server.
New-AzSqlServerFirewallRule -ResourceGroupName $dbresourcegroupname `
    -ServerName $servername `
    -FirewallRuleName "AllowClient" -StartIpAddress $clientIP -EndIpAddress $clientIP

# Creeate the database in the server.
New-AzSqlDatabase  -ResourceGroupName $dbresourcegroupname `
    -ServerName $servername `
    -DatabaseName $databasename `
    -RequestedServiceObjectiveName "S0"

Write-Host "Server name is $servername"

提示

如果您在公司防火牆後方,開發電腦的 IP 位址可能是無法向網際網路公開的 IP 位址。If you are behind a corporate firewall, the IP address of your development computer may not be IP address exposed to the internet. 若要確認用於防火牆規則的資料庫 IP 位址是否正確,請前往 Azure 入口網站,並在 SQL Database 區段中尋找您的資料庫。To verify that the database has the correct IP address for the firewall rule, go to the Azure portal and find your database in the SQL Databases section. 按一下其名稱,然後在 [概觀] 區段中按一下 [設定伺服器防火牆]。Click on its name, then in the Overview section click "Set server firewall". 「用戶端 IP 位址」是您開發機器的 IP 位址。"Client IP address" is the IP address of your development machine. 請確定它符合 "AllowClient" 規則中的 IP 位址。Ensure that it matches the IP address in the "AllowClient" rule.

更新 Web 設定Update the web config

回到 FabrikamFiber.Web 專案,更新 web.config 檔案中的連接字串以指向容器中的 SQL Server。Back in the FabrikamFiber.Web project, update the connection string in the web.config file, to point to the SQL Server in the container. 更新連接字串的 Server 這個部分,改為之前指令碼所建立的伺服器名稱。Update the Server part of the connection string to be the server name created by the previous script. 它應該會類似 "fab-fiber-751718376.database.windows.net"。It should be something like "fab-fiber-751718376.database.windows.net".

<add name="FabrikamFiber-Express" connectionString="Server=<server name>,1433;Initial Catalog=call-center-db;Persist Security Info=False;User ID=ServerAdmin;Password=Password@123;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
<add name="FabrikamFiber-DataWarehouse" connectionString="Server=<server name>,1433;Initial Catalog=call-center-db;Persist Security Info=False;User ID=ServerAdmin;Password=Password@123;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
  

注意

您可以使用任何慣用的 SQL Server 來進行本機偵錯,只要能夠從您的主機連線到該 SQL Server 即可。You can use any SQL Server you prefer for local debugging, as long as it is reachable from your host. 不過,localdb 不支援 container -> host 通訊。However, localdb does not support container -> host communication. 在建置 Web 應用程式的發行組建時,如果您想要使用不同的 SQL 資料庫,請在 web.release.config 檔案中新增另一個連接字串。If you want to use a different SQL database when building a release build of your web application, add another connection string to your web.release.config file.

在本機執行容器化的應用程式Run the containerized application locally

F5 在本機 Service Fabric 開發叢集中執行容器中的應用程式並進行偵錯。Press F5 to run and debug the application in a container on the local Service Fabric development cluster. 如果出現訊息方塊,詢問您是否要將 Visual Studio 專案目錄的讀取和執行權限授與 'ServiceFabricAllowedUsers' 群組,請按一下 [是] 。Click Yes if presented with a message box asking to grant 'ServiceFabricAllowedUsers' group read and execute permissions to your Visual Studio project directory.

建立容器登錄庫Create a container registry

現在應用程式是在本機執行,可以開始準備部署至 Azure。Now that the application runs locally, start preparing to deploy to Azure. 容器映像需要存放在容器登錄中。Container images need to be stored in a container registry. 使用下列指令碼建立 Azure 容器登錄Create an Azure container registry using the following script. 其他 Azure 訂用帳戶會看到容器登錄名稱,因此此名稱必須是唯一的。The container registry name is visible by other Azure subscriptions, so it must be unique. 將應用程式部署到 Azure 前,需將容器映像推送至此登錄。Before deploying the application to Azure, you push the container image to this registry. 當應用程式部署到 Azure 中的叢集時,會從此登錄提取容器映像。When the application deploys to the cluster in Azure, the container image is pulled from this registry.

# Variables
$acrresourcegroupname = "fabrikam-acr-group"
$location = "southcentralus"
$registryname="fabrikamregistry$(Get-Random)"

New-AzResourceGroup -Name $acrresourcegroupname -Location $location

$registry = New-AzContainerRegistry -ResourceGroupName $acrresourcegroupname -Name $registryname -EnableAdminUser -Sku Basic

在 Azure 中建立 Service Fabric 叢集Create a Service Fabric cluster on Azure

Service Fabric 應用程式執行於叢集,也就是一組連接網路的虛擬或實體機器。Service Fabric applications run on a cluster, a network-connected set of virtual or physical machines. 您需要先在 Azure 中建立 Service Fabric 叢集,才能將應用程式部署至 Azure。Before you can deploy the application to Azure, create a Service Fabric cluster in Azure.

您可以:You can:

  • 從 Visual Studio 建立測試叢集。Create a test cluster from Visual Studio. 此選項可讓您使用慣用的組態,直接從 Visual Studio 建立安全的叢集。This option allows you to create a secure cluster directly from Visual Studio with your preferred configurations.
  • 從範本建立安全叢集Create a secure cluster from a template

本教學課程是從 Visual Studio建立叢集,這非常適合用於測試案例。This tutorial creates a cluster from Visual Studio, which is ideal for test scenarios. 如果您用其他方式建立叢集或使用現有叢集,可以複製和貼上您的連線端點,或從訂用帳戶中選擇它。If you create a cluster some other way or use an existing cluster, you can copy and paste your connection endpoint or choose it from your subscription.

開始之前,在 [方案總管] 中,開啟 FabrikamFiber.Web->PackageRoot->ServiceManifest.xml。Before starting, open FabrikamFiber.Web->PackageRoot->ServiceManifest.xml in the Solution Explorer. 記下 [端點] 中列出的 Web 前端連接埠。Take note of the port for the web front-end listed in Endpoint.

建立叢集時,When creating the cluster,

  1. 以滑鼠右鍵按一下 [方案總管] 中的 [FabrikamFiber.CallCenterApplication] 應用程式專案,然後選擇 [發佈] 。Right-click on the FabrikamFiber.CallCenterApplication application project in the Solution Explorer and choose Publish.

  2. 使用您的 Azure 帳戶登入,以便存取您的訂用帳戶。Sign in by using your Azure account so that you can have access to your subscription(s).

  3. 選取 [連線端點] 下拉式清單,然後選取 [建立新叢集...] 選項。Select the dropdown for the Connection Endpoint and select the Create New Cluster... option.

  4. 在 [建立叢集] 對話方塊中,修改下列設定:In the Create cluster dialog, modify the following settings:

    a.a. 在 [叢集名稱] 欄位中指定叢集的名稱,以及您想要使用的訂用帳戶和位置。Specify the name of your cluster in the Cluster Name field, as well as the subscription and location you want to use. 記下叢集資源群組的名稱。Take note of the name of your cluster resource group.

    b.b. 選用:您可以修改節點數目。Optional: You can modify the number of nodes. 根據預設,您有三個節點,這是測試 Service Fabric 案例所需的最少節點數。By default you have three nodes, the minimum required for testing Service Fabric scenarios.

    c.c. 選取 [憑證] 索引標籤。在此索引標籤中,輸入要用來保護叢集憑證的密碼。Select the Certificate tab. In this tab, type a password to use to secure the certificate of your cluster. 此憑證可協助保護您的叢集。This certificate helps make your cluster secure. 您也可以修改您要儲存憑證的路徑。You can also modify the path to where you want to save the certificate. Visual Studio 也可以為您匯入憑證,因為這是要將應用程式發佈至叢集所需的項目。Visual Studio can also import the certificate for you, since this is a required step to publish the application to the cluster.

    d.d. 選取 [VM 詳細資料] 索引標籤。指定您想用於組成叢集之虛擬機器 (VM) 的密碼。Select the VM Detail tab. Specify the password you would like to use for the Virtual Machines (VM) that make up the cluster. 使用者名稱和密碼可用來從遠端連線到 VM。The user name and password can be used to remotely connect to the VMs. 您也必須選取 VM 機器大小,並可視需要變更 VM 映像。You must also select a VM machine size and can change the VM image if needed.

    重要

    選擇支援執行容器的 SKU。Choose a SKU that supports running containers. 在叢集節點上的 Windows Server 作業系統必須相容於您容器的 Windows Server 作業系統。The Windows Server OS on your cluster nodes must be compatible with the Windows Server OS of your container. 若要深入了解,請參閱 Windows Server 容器作業系統和主機作業系統的相容性To learn more, see Windows Server container OS and host OS compatibility. 根據預設,本教學課程會建立以 Windows Server 2016 LTSC 為基礎的 Docker 映像。By default, this tutorial creates a Docker image based on Windows Server 2016 LTSC. 以此映像為基礎的容器將會在叢集上執行,而叢集會透過具有容器的 Windows Server 2016 Datacenter 來建立。Containers based on this image will run on clusters created with Windows Server 2016 Datacenter with Containers. 不過,如果您建立的叢集或使用的現有叢集,是以具有容器的 Windows Server Datacenter Core 1709 為基礎,您必須變更容器所依據的 Windows Server 作業系統映像。However, if you create a cluster or use an existing cluster based on Windows Server Datacenter Core 1709 with Containers, you must change the Windows Server OS image that the container is based on. 開啟 FabrikamFiber.Web 專案中的 [Dockerfile] ,為現有的 FROM 陳述式加上註解 (以 windowsservercore-ltsc 為基礎),並對以 windowsservercore-1709 為基礎的 FROM 陳述式取消註解。Open the Dockerfile in the FabrikamFiber.Web project, comment out the existing FROM statement (based on windowsservercore-ltsc) and uncomment the FROM statement based on windowsservercore-1709.

    e.e. 在 [進階] 索引標籤中,列出應用程式連接埠,這是叢集部署時要在負載平衡器中開啟的連接埠。In the Advanced tab, list the application port to open in the load balancer when the cluster deploys. 這是您在開始建立叢集之前所記下的連接埠。This is the port that you took note of before starting creating the cluster. 您也可以新增現有的 Application Insights 金鑰,此金鑰會用於路由傳送應用程式記錄檔。You can also add an existing Application Insights key to be used to route application log files to.

    f.f. 當您完成設定修改時,請選取 [建立] 按鈕。When you are done modifying settings, select the Create button.

  5. 建立作業需要幾分鐘才能完成;輸出視窗會指出叢集何時建立完成。Creation takes several minutes to complete; the output window will indicate when the cluster is fully created.

允許在 Azure 中執行的應用程式存取 SQL 資料庫Allow your application running in Azure to access the SQL DB

您先前已建立 SQL 防火牆規則,讓在本機執行的應用程式有存取權。Previously, you created a SQL firewall rule to give access to your application running locally. 接著,您需要讓在 Azure 中執行的應用程式存取 SQL 資料庫。Next, you need to enable the application running in Azure to access the SQL DB. 為 Service Fabric 叢集建立虛擬網路服務端點,然後再建立規則以允許該端點存取 SQL 資料庫。Create a virtual network service endpoint for the Service Fabric cluster and then create a rule to allow that endpoint to access the SQL DB. 請務必指定建立叢集時,您所記下的叢集資源群組變數。Be sure to specify the cluster resource group variable that you took note of when creating the cluster.

# Create a virtual network service endpoint
$clusterresourcegroup = "<cluster resource group>"
$resource = Get-AzResource -ResourceGroupName $clusterresourcegroup -ResourceType Microsoft.Network/virtualNetworks | Select-Object -first 1
$vnetName = $resource.Name

Write-Host 'Virtual network name: ' $vnetName 

# Get the virtual network by name.
$vnet = Get-AzVirtualNetwork `
  -ResourceGroupName $clusterresourcegroup `
  -Name              $vnetName

Write-Host "Get the subnet in the virtual network:"

# Get the subnet, assume the first subnet contains the Service Fabric cluster.
$subnet = Get-AzVirtualNetworkSubnetConfig -VirtualNetwork $vnet | Select-Object -first 1

$subnetName = $subnet.Name
$subnetID = $subnet.Id
$addressPrefix = $subnet.AddressPrefix

Write-Host "Subnet name: " $subnetName " Address prefix: " $addressPrefix " ID: " $subnetID

# Assign a Virtual Service endpoint 'Microsoft.Sql' to the subnet.
$vnet = Set-AzVirtualNetworkSubnetConfig `
  -Name            $subnetName `
  -AddressPrefix   $addressPrefix `
  -VirtualNetwork  $vnet `
  -ServiceEndpoint Microsoft.Sql | Set-AzVirtualNetwork

$vnet.Subnets[0].ServiceEndpoints;  # Display the first endpoint.

# Add a SQL DB firewall rule for the virtual network service endpoint
$subnet = Get-AzVirtualNetworkSubnetConfig `
  -Name           $subnetName `
  -VirtualNetwork $vnet;

$VNetRuleName="ServiceFabricClusterVNetRule"
$vnetRuleObject1 = New-AzSqlServerVirtualNetworkRule `
  -ResourceGroupName      $dbresourcegroupname `
  -ServerName             $servername `
  -VirtualNetworkRuleName $VNetRuleName `
  -VirtualNetworkSubnetId $subnetID;

將應用程式部署至 AzureDeploy the application to Azure

現在應用程式已備妥,您可以直接從 Visual Studio 將其部署到 Azure 中的叢集。Now that the application is ready, you can deploy it to the cluster in Azure directly from Visual Studio. 以滑鼠右鍵按一下 [方案總管] 中的 [FabrikamFiber.CallCenterApplication] 應用程式專案,然後選擇 [發佈] 。In Solution Explorer, right-click the FabrikamFiber.CallCenterApplication application project and select Publish. 在 [連線端點] 中選取您先前建立的叢集端點。In Connection Endpoint, select the endpoint of the cluster that you created previously. 在 [Azure 容器登錄] 中,選取您先前建立的容器登錄。In Azure Container Registry, select the container registry that you created previously. 按一下 [發佈] 將應用程式發佈至 Azure 中的叢集。Click Publish to deploy the application to the cluster in Azure.

發佈應用程式

輸出視窗會顯示部署進度。Follow the deployment progress in the output window. 部署應用程式後,開啟瀏覽器並鍵入叢集位址和應用程式連接埠。When the application is deployed, open a browser and type in the cluster address and application port. 例如,http://fabrikamfibercallcenter.southcentralus.cloudapp.azure.com:8659/。For example, http://fabrikamfibercallcenter.southcentralus.cloudapp.azure.com:8659/.

Fabrikam Web 範例

設定 Service Fabric 叢集的持續整合和部署 (CI/CD)Set up Continuous Integration and Deployment (CI/CD) with a Service Fabric cluster

若要了解如何使用 Azure DevOps 設定對 Service Fabric 叢集的 CI/CD 應用程式部署,請參閱教學課程:透過 CI/CD 將應用程式部署至 Service Fabric 叢集To learn how to use Azure DevOps to configure CI/CD application deployment to a Service Fabric cluster, see Tutorial: Deploy an application with CI/CD to a Service Fabric cluster. 該教學課程中說明的程序與此 (FabrikamFiber) 專案的相同,只要略過下載投票範例的步驟,並將 FabrikamFiber 取代為存放庫名稱 (而不是「投票」) 即可。The process described in the tutorial is the same for this (FabrikamFiber) project, just skip downloading the Voting sample and substitute FabrikamFiber as the repository name instead of Voting.

清除資源Clean up resources

完成時,請務必移除您建立的所有資源。If you're done, be sure to remove all the resources you created. 最簡單的方式是移除資源群組,包括 Service Fabric 叢集、Azure SQL 資料庫、Azure 容器登錄。The simplest way to is to remove the resources groups that contain the Service Fabric cluster, Azure SQL DB, and Azure Container Registry.

$dbresourcegroupname = "fabrikam-fiber-db-group"
$acrresourcegroupname = "fabrikam-acr-group"
$clusterresourcegroupname="fabrikamcallcentergroup"

# Remove the Azure SQL DB
Remove-AzResourceGroup -Name $dbresourcegroupname

# Remove the container registry
Remove-AzResourceGroup -Name $acrresourcegroupname

# Remove the Service Fabric cluster
Remove-AzResourceGroup -Name $clusterresourcegroupname

後續步驟Next steps

在本教學課程中,您已了解如何:In this tutorial, you learned how to:

  • 使用 Visual Studio 將現有應用程式容器化Containerize an existing application using Visual Studio
  • 建立 Azure SQL 資料庫Create an Azure SQL database
  • 建立 Azure 容器登錄Create an Azure container registry
  • 將 Service Fabric 應用程式部署至 AzureDeploy a Service Fabric application to Azure

在本教學課程的下一個部分,了解如何將具有 CI/CD 的容器應用程式部署到 Service Fabric 叢集In the next part of the tutorial, learn how to Deploy a container application with CI/CD to a Service Fabric cluster.

m-web-page.pngm-web-page.png fabrikam-web-page-deployed: media/service-fabric-host-app-in-a-container/fabrikam-web-page-deployed.png publish-app: media/service-fabric-host-app-in-a-container/publish-app.png