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

如何在 Azure 中均衡 Windows 虚拟机负载以创建高可用性应用程序How to load balance Windows virtual machines in Azure to create a highly available application

负载均衡通过将传入请求分布到多个虚拟机来提供更高级别的可用性。Load balancing provides a higher level of availability by spreading incoming requests across multiple virtual machines. 本教程介绍 Azure 负载均衡器的不同组件,这些组件用于分发流量和提供高可用性。In this tutorial, you learn about the different components of the Azure load balancer that distribute traffic and provide high availability. 学习如何:You learn how to:

  • 创建 Azure 负载均衡器Create an Azure load balancer
  • 创建负载均衡器运行状况探测Create a load balancer health probe
  • 创建负载均衡器流量规则Create load balancer traffic rules
  • 使用自定义脚本扩展创建基本的 IIS 站点Use the Custom Script Extension to create a basic IIS site
  • 创建虚拟机并将其附加到负载均衡器Create virtual machines and attach to a load balancer
  • 查看运行中的负载均衡器View a load balancer in action
  • 从负载均衡器中添加和删除 VMAdd and remove VMs from a load balancer

本教程需要 Azure PowerShell 模块 3.6 或更高版本。This tutorial requires the Azure PowerShell module version 3.6 or later. 可以运行 Get-Module -ListAvailable AzureRM 来查找版本。Run Get-Module -ListAvailable AzureRM to find the version. 如果需要升级,请参阅安装 Azure PowerShell 模块If you need to upgrade, see Install Azure PowerShell module.

Azure 负载均衡器概述Azure load balancer overview

Azure 负载均衡器是位于第 4 层(TCP、UDP)的负载均衡器,通过在正常运行的 VM 之间分发传入流量提供高可用性。An Azure load balancer is a Layer-4 (TCP, UDP) load balancer that provides high availability by distributing incoming traffic among healthy VMs. 负载均衡器的运行状况探测监视每个 VM 上的给定端口,并仅将流量分发给可操作的 VM。A load balancer health probe monitors a given port on each VM and only distributes traffic to an operational VM.

定义包含一个或多个公共 IP 地址的前端 IP 配置。You define a front-end IP configuration that contains one or more public IP addresses. 利用此前端 IP 配置,可通过 Internet 访问负载均衡器和应用程序。This front-end IP configuration allows your load balancer and applications to be accessible over the Internet.

虚拟机使用其虚拟网络接口卡 (NIC) 连接到负载均衡器。Virtual machines connect to a load balancer using their virtual network interface card (NIC). 若要向 VM 分发流量,后端地址池需包含连接到负载均衡器的虚拟 NIC 的 IP 地址。To distribute traffic to the VMs, a back-end address pool contains the IP addresses of the virtual (NICs) connected to the load balancer.

若要控制流量流,需为映射到 VM 的特定端口和协议定义负载均衡器规则。To control the flow of traffic, you define load balancer rules for specific ports and protocols that map to your VMs.

创建 Azure 负载均衡器Create Azure load balancer

本部分详细介绍如何创建和配置负载均衡器的每个组件。This section details how you can create and configure each component of the load balancer. 创建负载均衡器之前,需使用 New-AzureRmResourceGroup 创建资源组。Before you can create your load balancer, create a resource group with New-AzureRmResourceGroup. 以下示例在“EastUS”位置创建名为“myResourceGroupLoadBalancer”的资源组:The following example creates a resource group named myResourceGroupLoadBalancer in the EastUS location:

New-AzureRmResourceGroup `
  -ResourceGroupName myResourceGroupLoadBalancer `
  -Location EastUS

创建公共 IP 地址Create a public IP address

若要通过 Internet 访问应用,需要负载均衡器的一个公共 IP 地址。To access your app on the Internet, you need a public IP address for the load balancer. 使用 New-AzureRmPublicIpAddress 创建一个公共 IP 地址。Create a public IP address with New-AzureRmPublicIpAddress. 以下示例在“myResourceGroupLoadBalancer”资源组中创建名为“myPublicIP”的公共 IP 地址:The following example creates a public IP address named myPublicIP in the myResourceGroupLoadBalancer resource group:

$publicIP = New-AzureRmPublicIpAddress `
  -ResourceGroupName myResourceGroupLoadBalancer `
  -Location EastUS `
  -AllocationMethod Static `
  -Name myPublicIP

创建负载均衡器Create a load balancer

使用 New-AzureRmLoadBalancerFrontendIpConfig 创建一个前端 IP 地址。Create a frontend IP address with New-AzureRmLoadBalancerFrontendIpConfig. 以下示例创建名为“myFrontEndPool”的前端 IP 地址:The following example creates a frontend IP address named myFrontEndPool:

$frontendIP = New-AzureRmLoadBalancerFrontendIpConfig `
  -Name myFrontEndPool `
  -PublicIpAddress $publicIP

使用 New-AzureRmLoadBalancerBackendAddressPoolConfig 创建一个后端地址池。Create a backend address pool with New-AzureRmLoadBalancerBackendAddressPoolConfig. 以下示例创建名为“myBackEndPool”的后端地址池:The following example creates a backend address pool named myBackEndPool:

$backendPool = New-AzureRmLoadBalancerBackendAddressPoolConfig -Name myBackEndPool

现在,使用 New-AzureRmLoadBalancer 创建负载均衡器。Now, create the load balancer with New-AzureRmLoadBalancer. 以下示例使用“myPublicIP”地址创建名为“myLoadBalancer”的负载均衡器:The following example creates a load balancer named myLoadBalancer using the myPublicIP address:

$lb = New-AzureRmLoadBalancer `
  -ResourceGroupName myResourceGroupLoadBalancer `
  -Name myLoadBalancer `
  -Location EastUS `
  -FrontendIpConfiguration $frontendIP `
  -BackendAddressPool $backendPool

创建运行状况探测器Create a health probe

若要允许负载均衡器监视应用的状态,可以使用运行状况探测器。To allow the load balancer to monitor the status of your app, you use a health probe. 运行状况探测器基于其对运行状况检查的响应,从负载均衡器中动态添加或删除 VM。The health probe dynamically adds or removes VMs from the load balancer rotation based on their response to health checks. 默认情况下,在 15 秒时间间隔内发生两次连续的故障后,将从负载均衡器分布中删除 VM。By default, a VM is removed from the load balancer distribution after two consecutive failures at 15-second intervals. 可以为应用创建基于协议或特定运行状况检查页面的运行状况探测器。You create a health probe based on a protocol or a specific health check page for your app.

以下示例创建一个 TCP 探测。The following example creates a TCP probe. 还可创建自定义 HTTP 探测,以便执行更精细的运行状况检查。You can also create custom HTTP probes for more fine grained health checks. 使用自定义 HTTP 探测时,必须创建运行状况检查页,例如 healthcheck.aspx。When using a custom HTTP probe, you must create the health check page, such as healthcheck.aspx. 探测必须为负载均衡器返回 HTTP 200 OK 响应,以保持主机处于旋转状态。The probe must return an HTTP 200 OK response for the load balancer to keep the host in rotation.

若要创建 TCP 运行状况探测,请使用 Add-AzureRmLoadBalancerProbeConfigTo create a TCP health probe, you use Add-AzureRmLoadBalancerProbeConfig. 以下示例创建名为“myHealthProbe”的运行状况探测,用于监视每个 VM:The following example creates a health probe named myHealthProbe that monitors each VM:

Add-AzureRmLoadBalancerProbeConfig `
  -Name myHealthProbe `
  -LoadBalancer $lb `
  -Protocol tcp `
  -Port 80 `
  -IntervalInSeconds 15 `
  -ProbeCount 2

使用 Set-AzureRmLoadBalancer 更新负载均衡器:Update the load balancer with Set-AzureRmLoadBalancer:

Set-AzureRmLoadBalancer -LoadBalancer $lb

创建负载均衡器规则Create a load balancer rule

负载均衡器规则用于定义将流量分配给 VM 的方式。A load balancer rule is used to define how traffic is distributed to the VMs. 定义传入流量的前端 IP 配置和后端 IP 池以接收流量,同时定义所需源和目标端口。You define the front-end IP configuration for the incoming traffic and the back-end IP pool to receive the traffic, along with the required source and destination port. 若要确保仅正常运行的 VM 接收流量,还需定义要使用的运行状况探测。To make sure only healthy VMs receive traffic, you also define the health probe to use.

使用 Add-AzureRmLoadBalancerRuleConfig 创建一个负载均衡器规则。Create a load balancer rule with Add-AzureRmLoadBalancerRuleConfig. 以下示例创建名为“myLoadBalancerRule”的负载均衡器规则并平衡端口 80 上的流量:The following example creates a load balancer rule named myLoadBalancerRule and balances traffic on port 80:

$probe = Get-AzureRmLoadBalancerProbeConfig -LoadBalancer $lb -Name myHealthProbe

Add-AzureRmLoadBalancerRuleConfig `
  -Name myLoadBalancerRule `
  -LoadBalancer $lb `
  -FrontendIpConfiguration $lb.FrontendIpConfigurations[0] `
  -BackendAddressPool $lb.BackendAddressPools[0] `
  -Protocol Tcp `
  -FrontendPort 80 `
  -BackendPort 80 `
  -Probe $probe

使用 Set-AzureRmLoadBalancer 更新负载均衡器:Update the load balancer with Set-AzureRmLoadBalancer:

Set-AzureRmLoadBalancer -LoadBalancer $lb

配置虚拟网络Configure virtual network

需要先创建支持的虚拟网络资源,才能部署某些 VM 和测试均衡器。Before you deploy some VMs and can test your balancer, create the supporting virtual network resources. 有关虚拟网络的详细信息,请参阅管理 Azure 虚拟网络教程。For more information about virtual networks, see the Manage Azure Virtual Networks tutorial.

创建网络资源Create network resources

使用 New-AzureRmVirtualNetwork 创建虚拟网络。Create a virtual network with New-AzureRmVirtualNetwork. 以下示例创建具有“mySubnet”的名为“myVnet”的虚拟网络:The following example creates a virtual network named myVnet with mySubnet:

# Create subnet config
$subnetConfig = New-AzureRmVirtualNetworkSubnetConfig `
  -Name mySubnet `
  -AddressPrefix 192.168.1.0/24

# Create the virtual network
$vnet = New-AzureRmVirtualNetwork `
  -ResourceGroupName myResourceGroupLoadBalancer `
  -Location EastUS `
  -Name myVnet `
  -AddressPrefix 192.168.0.0/16 `
  -Subnet $subnetConfig

使用 New-AzureRmNetworkSecurityRuleConfig 创建网络安全组规则,并使用 New-AzureRmNetworkSecurityGroup 创建网络安全组。Create a network security group rule with New-AzureRmNetworkSecurityRuleConfig, then create a network security group with New-AzureRmNetworkSecurityGroup. 使用 Set-AzureRmVirtualNetworkSubnetConfig 将网络安全组添加到子网,然后使用 Set-AzureRmVirtualNetwork 更新虚拟网络。Add the network security group to the subnet with Set-AzureRmVirtualNetworkSubnetConfig and then update the virtual network with Set-AzureRmVirtualNetwork.

以下示例创建一个名为“myNetworkSecurityGroup”的网络安全组规则,并将其应用于 mySubnet:The following example creates a network security group rule named myNetworkSecurityGroup and applies it to mySubnet:

# Create security rule config
$nsgRule = New-AzureRmNetworkSecurityRuleConfig `
  -Name myNetworkSecurityGroupRule `
  -Protocol Tcp `
  -Direction Inbound `
  -Priority 1001 `
  -SourceAddressPrefix * `
  -SourcePortRange * `
  -DestinationAddressPrefix * `
  -DestinationPortRange 80 `
  -Access Allow

# Create the network security group
$nsg = New-AzureRmNetworkSecurityGroup `
  -ResourceGroupName myResourceGroupLoadBalancer `
  -Location EastUS `
  -Name myNetworkSecurityGroup `
  -SecurityRules $nsgRule

# Apply the network security group to a subnet
Set-AzureRmVirtualNetworkSubnetConfig `
  -VirtualNetwork $vnet `
  -Name mySubnet `
  -NetworkSecurityGroup $nsg `
  -AddressPrefix 192.168.1.0/24

# Update the virtual network
Set-AzureRmVirtualNetwork -VirtualNetwork $vnet

使用 New-AzureRmNetworkInterface 创建虚拟 NIC。Virtual NICs are created with New-AzureRmNetworkInterface. 以下示例创建三个虚拟 NIC。The following example creates three virtual NICs. (在以下步骤中为应用创建的每个 VM 各使用一个虚拟 NIC)。(One virtual NIC for each VM you create for your app in the following steps). 可随时创建其他虚拟 NIC 和 VM,并将其添加到负载均衡器:You can create additional virtual NICs and VMs at any time and add them to the load balancer:

for ($i=1; $i -le 3; $i++)
{
   New-AzureRmNetworkInterface `
     -ResourceGroupName myResourceGroupLoadBalancer `
     -Name myNic$i `
     -Location EastUS `
     -Subnet $vnet.Subnets[0] `
     -LoadBalancerBackendAddressPool $lb.BackendAddressPools[0]
}

创建虚拟机Create virtual machines

要提高应用的高可用性,请将 VM 放置在可用性集中。To improve the high availability of your app, place your VMs in an availability set.

使用 New-AzureRmAvailabilitySet 创建一个可用性集。Create an availability set with New-AzureRmAvailabilitySet. 以下示例创建名为“myAvailabilitySet”的可用性集:The following example creates an availability set named myAvailabilitySet:

$availabilitySet = New-AzureRmAvailabilitySet `
  -ResourceGroupName myResourceGroupLoadBalancer `
  -Name myAvailabilitySet `
  -Location EastUS `
  -Managed `
  -PlatformFaultDomainCount 3 `
  -PlatformUpdateDomainCount 2

使用 New-AzureRmNetworkInterface 设置 VM 的管理员用户名和密码:Set an administrator username and password for the VMs with Get-Credential:

$cred = Get-Credential

现在,可使用 New-AzureRmVM 创建 VM。Now you can create the VMs with New-AzureRmVM. 下例创建 3 个 VM:The following example creates three VMs:

for ($i=1; $i -le 3; $i++)
{
  $vm = New-AzureRmVMConfig `
    -VMName myVM$i `
    -VMSize Standard_D1 `
    -AvailabilitySetId $availabilitySet.Id
  $vm = Set-AzureRmVMOperatingSystem `
    -VM $vm `
    -Windows `
    -ComputerName myVM$i `
    -Credential $cred `
    -ProvisionVMAgent `
    -EnableAutoUpdate
  $vm = Set-AzureRmVMSourceImage `
    -VM $vm `
    -PublisherName MicrosoftWindowsServer `
    -Offer WindowsServer `
    -Skus 2016-Datacenter `
    -Version latest
  $vm = Set-AzureRmVMOSDisk `
    -VM $vm `
    -Name myOsDisk$i `
    -DiskSizeInGB 128 `
    -CreateOption FromImage `
    -Caching ReadWrite
  $nic = Get-AzureRmNetworkInterface `
    -ResourceGroupName myResourceGroupLoadBalancer `
    -Name myNic$i
  $vm = Add-AzureRmVMNetworkInterface -VM $vm -Id $nic.Id
  New-AzureRmVM `
    -ResourceGroupName myResourceGroupLoadBalancer `
    -Location EastUS `
    -VM $vm
}

创建和配置所有三个 VM 需要几分钟时间。It takes a few minutes to create and configure all three VMs.

使用自定义脚本扩展安装 IISInstall IIS with Custom Script Extension

在有关如何自定义 Windows 虚拟机的上一个教程中,已了解如何使用 Windows 的自定义脚本扩展自动执行 VM 自定义。In a previous tutorial on How to customize a Windows virtual machine, you learned how to automate VM customization with the Custom Script Extension for Windows. 可使用相同的方法在 VM 上安装和配置 IIS。You can use the same approach to install and configure IIS on your VMs.

使用 Set-AzureRmVMExtension 安装自定义脚本扩展。Use Set-AzureRmVMExtension to install the Custom Script Extension. 该扩展运行 powershell Add-WindowsFeature Web-Server 以安装 IIS Web 服务器,并更新“Default.htm”页以显示 VM 的主机名:The extension runs powershell Add-WindowsFeature Web-Server to install the IIS webserver and then updates the Default.htm page to show the hostname of the VM:

for ($i=1; $i -le 3; $i++)
{
   Set-AzureRmVMExtension `
     -ResourceGroupName myResourceGroupLoadBalancer `
     -ExtensionName IIS `
     -VMName myVM$i `
     -Publisher Microsoft.Compute `
     -ExtensionType CustomScriptExtension `
     -TypeHandlerVersion 1.4 `
     -SettingString '{"commandToExecute":"powershell Add-WindowsFeature Web-Server; powershell Add-Content -Path \"C:\\inetpub\\wwwroot\\Default.htm\" -Value $($env:computername)"}' `
     -Location EastUS
}

测试负载均衡器Test load balancer

使用 Get-AzureRmPublicIPAddress 获取负载均衡器的公共 IP 地址。Obtain the public IP address of your load balancer with Get-AzureRmPublicIPAddress. 以下示例获取前面创建的“myPublicIP”的 IP 地址:The following example obtains the IP address for myPublicIP created earlier:

Get-AzureRmPublicIPAddress `
  -ResourceGroupName myResourceGroupLoadBalancer `
  -Name myPublicIP | select IpAddress

然后,可将公共 IP 地址输入 web 浏览器中。You can then enter the public IP address in to a web browser. 随即显示网站,包括负载均衡器将流量分发到的 VM 的主机名,如下例所示:The website is displayed, including the hostname of the VM that the load balancer distributed traffic to as in the following example:

运行 IIS 网站

若要查看负载均衡器如何在运行应用的所有 3 个 VM 之间分配流量,可强制刷新 web 浏览器。To see the load balancer distribute traffic across all three VMs running your app, you can force-refresh your web browser.

添加和删除 VMAdd and remove VMs

建议对运行应用的 VM 执行维护,例如安装 OS 更新。You may need to perform maintenance on the VMs running your app, such as installing OS updates. 若要应对应用增加的流量,建议添加更多 VM。To deal with increased traffic to your app, you may need to add additional VMs. 本部分演示了如何在负载均衡器中删除或添加 VM。This section shows you how to remove or add a VM from the load balancer.

从负载均衡器中删除 VMRemove a VM from the load balancer

使用 Get-AzureRmNetworkInterface 获取网络接口卡,然后将虚拟 NIC 的 LoadBalancerBackendAddressPools 属性设置为“$null”。Get the network interface card with Get-AzureRmNetworkInterface, then set the LoadBalancerBackendAddressPools property of the virtual NIC to $null. 最后,更新虚拟 NIC。Finally, update the virtual NIC.:

$nic = Get-AzureRmNetworkInterface `
    -ResourceGroupName myResourceGroupLoadBalancer `
    -Name myNic2
$nic.Ipconfigurations[0].LoadBalancerBackendAddressPools=$null
Set-AzureRmNetworkInterface -NetworkInterface $nic

若要查看负载均衡器如何在运行应用的其余两个 VM 之间分发流量,可强制刷新 web 浏览器。To see the load balancer distribute traffic across the remaining two VMs running your app you can force-refresh your web browser. 现在可以对 VM 执行维护,例如安装 OS 更新或执行 VM 重新启动。You can now perform maintenance on the VM, such as installing OS updates or performing a VM reboot.

将 VM 添加到负载均衡器Add a VM to the load balancer

执行 VM 维护后,或者如果需要扩展容量,请通过 Get-AzureRMLoadBalancer 将虚拟 NIC 的 LoadBalancerBackendAddressPools 属性设置为“BackendAddressPool”:After performing VM maintenance, or if you need to expand capacity, set the LoadBalancerBackendAddressPools property of the virtual NIC to the BackendAddressPool from Get-AzureRMLoadBalancer:

获取负载均衡器:Get the load balancer:

$lb = Get-AzureRMLoadBalancer `
    -ResourceGroupName myResourceGroupLoadBalancer `
    -Name myLoadBalancer 
$nic.IpConfigurations[0].LoadBalancerBackendAddressPools=$lb.BackendAddressPools[0]
Set-AzureRmNetworkInterface -NetworkInterface $nic

后续步骤Next steps

在本教程中,已创建负载均衡器并已将 VM 附加到它。In this tutorial, you created a load balancer and attached VMs to it. 你已了解如何:You learned how to:

  • 创建 Azure 负载均衡器Create an Azure load balancer
  • 创建负载均衡器运行状况探测Create a load balancer health probe
  • 创建负载均衡器流量规则Create load balancer traffic rules
  • 使用自定义脚本扩展创建基本的 IIS 站点Use the Custom Script Extension to create a basic IIS site
  • 创建虚拟机并将其附加到负载均衡器Create virtual machines and attach to a load balancer
  • 查看运行中的负载均衡器View a load balancer in action
  • 从负载均衡器中添加和删除 VMAdd and remove VMs from a load balancer

请转到下一教程,了解如何管理 VM 网络。Advance to the next tutorial to learn how to manage VM networking.