您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

教程:将 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 数据库中。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.CallCenterApplication” 。A 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. 还会向“FabrikamFiber.Web”项目添加一个“PackageRoot”目录,其中包含新 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 DBCreate 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 数据库We recommend Azure SQL Database. 若要在 Azure 中设置和运行托管的 SQL Server DB,请运行以下脚本。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 地址可能不是暴露于 Internet 的 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 数据库”部分找到数据库。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 进行本地调试,只要可通过主机访问。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. 如果出现一个消息框,请求授予“ServiceFabricAllowedUsers”组对Visual Studio 项目目录的读取和执行权限,请单击“是” 。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 OS 必须与容器的 Windows Server OS 兼容。The Windows Server OS on your cluster nodes must be compatible with the Windows Server OS of your container. 若要了解更多信息,请参阅 Windows Server 容器 OS 与主机 OS 的兼容性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 OS 映像。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-1709FROM 语句。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 DBAllow 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 DB。Next, you need to enable the application running in Azure to access the SQL DB. 为 Service Fabric 群集创建虚拟网络服务终结点,然后创建一个规则,允许该终结点访问 SQL DB。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) 项目相同,只需跳过下载 Voting 示例并将 FabrikamFiber 替换为存储库名称而不是 Voting。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 DB 和 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