快速入門:使用 Azure PowerShell 建立公用負載平衡器以平衡 VM 的負載Quickstart: Create a public load balancer to load balance VMs using Azure PowerShell

使用 Azure PowerShell 建立公用負載平衡器和三部虛擬機器,以開始使用 Azure Load Balancer。Get started with Azure Load Balancer by using Azure PowerShell to create a public load balancer and three virtual machines.

PrerequisitesPrerequisites

  • 具有有效訂用帳戶的 Azure 帳戶。An Azure account with an active subscription. 免費建立帳戶Create an account for free.
  • 已在本機安裝 Azure PowerShell 或 Azure Cloud ShellAzure PowerShell installed locally or Azure Cloud Shell

如果您選擇在本機安裝和使用 PowerShell,本文會要求使用 Azure PowerShell 模組版本 5.4.1 或更新版本。If you choose to install and use PowerShell locally, this article requires the Azure PowerShell module version 5.4.1 or later. 執行 Get-Module -ListAvailable Az 來了解安裝的版本。Run Get-Module -ListAvailable Az to find the installed version. 如果您需要升級,請參閱安裝 Azure PowerShell 模組If you need to upgrade, see Install Azure PowerShell module. 如果您在本機執行 PowerShell,則也需要執行 Connect-AzAccount 以建立與 Azure 的連線。If you're running PowerShell locally, you also need to run Connect-AzAccount to create a connection with Azure.

建立資源群組Create a resource group

Azure 資源群組是在其中部署與管理 Azure 資源的邏輯容器。An Azure resource group is a logical container into which Azure resources are deployed and managed.

使用 New-AzResourceGroup 來建立資源群組:Create a resource group with New-AzResourceGroup:

New-AzResourceGroup -Name 'CreatePubLBQS-rg' -Location 'eastus'


注意

建議對生產環境工作負載使用標準 SKU 負載平衡器。Standard SKU load balancer is recommended for production workloads. 如需 SKU 的詳細資訊,請參閱 Azure Load Balancer 的標準 SKUFor more information about skus, see Azure Load Balancer SKUs.

針對快速入門所建立的標準負載平衡器資源。

建立公用 IP 位址 - 標準Create a public IP address - Standard

使用 New-AzPublicIpAddress 建立公用 IP 位址。Use New-AzPublicIpAddress to create a public IP address.

$publicip = @{
    Name = 'myPublicIP'
    ResourceGroupName = 'CreatePubLBQS-rg'
    Location = 'eastus'
    Sku = 'Standard'
    AllocationMethod = 'static'
    Zone = 1,2,3
}
New-AzPublicIpAddress @publicip

若要在區域 1 中建立區域性公用 IP 位址,請使用下列命令:To create a zonal public IP address in zone 1, use the following command:

$publicip = @{
    Name = 'myPublicIP'
    ResourceGroupName = 'CreatePubLBQS-rg'
    Location = 'eastus'
    Sku = 'Standard'
    AllocationMethod = 'static'
    Zone = 1
}
New-AzPublicIpAddress @publicip

建立標準負載平衡器Create standard load balancer

本節將詳細說明如何建立及設定下列負載平衡器元件:This section details how you can create and configure the following components of the load balancer:

## Place public IP created in previous steps into variable. ##
$publicIp = Get-AzPublicIpAddress -Name 'myPublicIP' -ResourceGroupName 'CreatePubLBQS-rg'

## Create load balancer frontend configuration and place in variable. ##
$feip = New-AzLoadBalancerFrontendIpConfig -Name 'myFrontEnd' -PublicIpAddress $publicIp

## Create backend address pool configuration and place in variable. ##
$bepool = New-AzLoadBalancerBackendAddressPoolConfig -Name 'myBackEndPool'

## Create the health probe and place in variable. ##
$probe = @{
    Name = 'myHealthProbe'
    Protocol = 'http'
    Port = '80'
    IntervalInSeconds = '360'
    ProbeCount = '5'
    RequestPath = '/'
}
$healthprobe = New-AzLoadBalancerProbeConfig @probe

## Create the load balancer rule and place in variable. ##
$lbrule = @{
    Name = 'myHTTPRule'
    Protocol = 'tcp'
    FrontendPort = '80'
    BackendPort = '80'
    IdleTimeoutInMinutes = '15'
    FrontendIpConfiguration = $feip
    BackendAddressPool = $bePool
}
$rule = New-AzLoadBalancerRuleConfig @lbrule -EnableTcpReset -DisableOutboundSNAT

## Create the load balancer resource. ##
$loadbalancer = @{
    ResourceGroupName = 'CreatePubLBQS-rg'
    Name = 'myLoadBalancer'
    Location = 'eastus'
    Sku = 'Standard'
    FrontendIpConfiguration = $feip
    BackendAddressPool = $bePool
    LoadBalancingRule = $rule
    Probe = $healthprobe
}
New-AzLoadBalancer @loadbalancer

設定虛擬網路 - 標準Configure virtual network - Standard

請先建立支援的虛擬網路資源,才可部署 VM 並測試您的負載平衡器。Before you deploy VMs and test your load balancer, create the supporting virtual network resources.

建立後端虛擬機器的虛擬網路。Create a virtual network for the backend virtual machines.

建立網路安全性群組,以定義虛擬網路的輸入連線。Create a network security group to define inbound connections to your virtual network.

建立虛擬網路、網路安全性群組和堡壘主機Create virtual network, network security group, and bastion host

## Create backend subnet config ##
$subnet = @{
    Name = 'myBackendSubnet'
    AddressPrefix = '10.1.0.0/24'
}
$subnetConfig = New-AzVirtualNetworkSubnetConfig @subnet 

## Create Azure Bastion subnet. ##
$bastsubnet = @{
    Name = 'AzureBastionSubnet' 
    AddressPrefix = '10.1.1.0/24'
}
$bastsubnetConfig = New-AzVirtualNetworkSubnetConfig @bastsubnet

## Create the virtual network ##
$net = @{
    Name = 'myVNet'
    ResourceGroupName = 'CreatePubLBQS-rg'
    Location = 'eastus'
    AddressPrefix = '10.1.0.0/16'
    Subnet = $subnetConfig,$bastsubnetConfig
}
$vnet = New-AzVirtualNetwork @net

## Create public IP address for bastion host. ##
$ip = @{
    Name = 'myBastionIP'
    ResourceGroupName = 'CreatePubLBQS-rg'
    Location = 'eastus'
    Sku = 'Standard'
    AllocationMethod = 'Static'
}
$publicip = New-AzPublicIpAddress @ip

## Create bastion host ##
$bastion = @{
    ResourceGroupName = 'CreatePubLBQS-rg'
    Name = 'myBastion'
    PublicIpAddress = $publicip
    VirtualNetwork = $vnet
}
New-AzBastion @bastion -AsJob

## Create rule for network security group and place in variable. ##
$nsgrule = @{
    Name = 'myNSGRuleHTTP'
    Description = 'Allow HTTP'
    Protocol = '*'
    SourcePortRange = '*'
    DestinationPortRange = '80'
    SourceAddressPrefix = 'Internet'
    DestinationAddressPrefix = '*'
    Access = 'Allow'
    Priority = '2000'
    Direction = 'Inbound'
}
$rule1 = New-AzNetworkSecurityRuleConfig @nsgrule

## Create network security group ##
$nsg = @{
    Name = 'myNSG'
    ResourceGroupName = 'CreatePubLBQS-rg'
    Location = 'eastus'
    SecurityRules = $rule1
}
New-AzNetworkSecurityGroup @nsg

建立虛擬機器 - 標準Create virtual machines - Standard

在本節中,您將為負載平衡器的後端集區建立三個虛擬機器。In this section, you'll create the three virtual machines for the backend pool of the load balancer.

# Set the administrator and password for the VMs. ##
$cred = Get-Credential

## Place the virtual network into a variable. ##
$vnet = Get-AzVirtualNetwork -Name 'myVNet' -ResourceGroupName 'CreatePubLBQS-rg'

## Place the load balancer into a variable. ##
$lb = @{
    Name = 'myLoadBalancer'
    ResourceGroupName = 'CreatePubLBQS-rg'
}
$bepool = Get-AzLoadBalancer @lb  | Get-AzLoadBalancerBackendAddressPoolConfig

## Place the network security group into a variable. ##
$nsg = Get-AzNetworkSecurityGroup -Name 'myNSG' -ResourceGroupName 'CreatePubLBQS-rg'

## For loop with variable to create virtual machines for load balancer backend pool. ##
for ($i=1; $i -le 3; $i++)
{
## Command to create network interface for VMs ##
$nic = @{
    Name = "myNicVM$i"
    ResourceGroupName = 'CreatePubLBQS-rg'
    Location = 'eastus'
    Subnet = $vnet.Subnets[0]
    NetworkSecurityGroup = $nsg
    LoadBalancerBackendAddressPool = $bepool
}
$nicVM = New-AzNetworkInterface @nic

## Create a virtual machine configuration for VMs ##
$vmsz = @{
    VMName = "myVM$i"
    VMSize = 'Standard_DS1_v2'  
}
$vmos = @{
    ComputerName = "myVM$i"
    Credential = $cred
}
$vmimage = @{
    PublisherName = 'MicrosoftWindowsServer'
    Offer = 'WindowsServer'
    Skus = '2019-Datacenter'
    Version = 'latest'    
}
$vmConfig = New-AzVMConfig @vmsz `
    | Set-AzVMOperatingSystem @vmos -Windows `
    | Set-AzVMSourceImage @vmimage `
    | Add-AzVMNetworkInterface -Id $nicVM.Id

## Create the virtual machine for VMs ##
$vm = @{
    ResourceGroupName = 'CreatePubLBQS-rg'
    Location = 'eastus'
    VM = $vmConfig
    Zone = "$i"
}
New-AzVM @vm -AsJob
}

虛擬機器和堡壘主機的部署會以 PowerShell 作業的形式提交。The deployments of the virtual machines and bastion host are submitted as PowerShell jobs. 若要檢視作業的狀態,請使用 Get-JobTo view the status of the jobs, use Get-Job:

Get-Job

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
1      Long Running O… AzureLongRunni… Completed     True            localhost            New-AzBastion
2      Long Running O… AzureLongRunni… Completed     True            localhost            New-AzVM
3      Long Running O… AzureLongRunni… Completed     True            localhost            New-AzVM
4      Long Running O… AzureLongRunni… Completed     True            localhost            New-AzVM

注意

Azure 會針對未獲指派公用 IP 位址,或位於內部基本 Azure Load Balancer 後端集區的 Azure 虛擬機器,提供暫時 IP。Azure provides an ephemeral IP for Azure Virtual Machines which aren't assigned a public IP address, or are in the backend pool of an internal Basic Azure Load Balancer. 暫時 IP 機制提供無法設定的輸出 IP 位址。The ephemeral IP mechanism provides an outbound IP address that isn't configurable.

將公用 IP 位址指派給虛擬機器,或將虛擬機器放置於 Standard Load Balancer 的後端集區(不論是否有輸出規則)時,會停用暫時 IP。The ephemeral IP is disabled when a public IP address is assigned to the virtual machine or the virtual machine is placed in the backend pool of a Standard Load Balancer with or without outbound rules. 如果 Azure 虛擬網路 NAT 閘道資源已指派給虛擬機器的子網,則會停用暫時 IP。If a Azure Virtual Network NAT gateway resource is assigned to the subnet of the virtual machine, the ephemeral IP is disabled.

如需 Azure 中輸出連線的詳細資訊,請參閱 使用來源網路位址轉譯 (SNAT) 進行輸出連線。For more information on outbound connections in Azure, see Using Source Network Address Translation (SNAT) for outbound connections.

建立輸出規則設定Create outbound rule configuration

負載平衡器輸出規則會在後端集區中設定 VM 的輸出來源網路位址轉譯 (SNAT)。Load balancer outbound rules configure outbound source network address translation (SNAT) for VMs in the backend pool.

如需輸出連線詳細資訊,請參閱 Azure 中的輸出連線For more information on outbound connections, see Outbound connections in Azure.

建立輸出公用 IP 位址Create outbound public IP address

使用 New-AzPublicIpAddress 建立名為 myPublicIPOutbound 的標準區域備援公用 IP 位址。Use New-AzPublicIpAddress to create a standard zone redundant public IP address named myPublicIPOutbound.

$publicipout = @{
    Name = 'myPublicIPOutbound'
    ResourceGroupName = 'CreatePubLBQS-rg'
    Location = 'eastus'
    Sku = 'Standard'
    AllocationMethod = 'static'
    Zone = 1,2,3
}
New-AzPublicIpAddress @publicipout

若要在區域 1 中建立區域性公用 IP 位址,請使用下列命令:To create a zonal public IP address in zone 1, use the following command:

$publicipout = @{
    Name = 'myPublicIPOutbound'
    ResourceGroupName = 'CreatePubLBQS-rg'
    Location = 'eastus'
    Sku = 'Standard'
    AllocationMethod = 'static'
    Zone = 1
}
New-AzPublicIpAddress @publicipout

建立輸出設定Create outbound configuration

## Place public IP created in previous steps into variable. ##
$pubip = @{
    Name = 'myPublicIPOutbound'
    ResourceGroupName = 'CreatePubLBQS-rg'
}
$publicIp = Get-AzPublicIpAddress @pubip

## Get the load balancer configuration ##
$lbc = @{
    ResourceGroupName = 'CreatePubLBQS-rg'
    Name = 'myLoadBalancer'
}
$lb = Get-AzLoadBalancer @lbc

## Create the frontend configuration ##
$fe = @{
    Name = 'myFrontEndOutbound'
    PublicIPAddress = $publicIP
}
$lb | Add-AzLoadBalancerFrontendIPConfig @fe | Set-AzLoadBalancer

## Create the outbound backend address pool ##
$be = @{
    Name = 'myBackEndPoolOutbound'
}
$lb | Add-AzLoadBalancerBackendAddressPoolConfig @be | Set-AzLoadBalancer

## Apply the outbound rule configuration to the load balancer. ##
$rule = @{
    Name = 'myOutboundRule'
    AllocatedOutboundPort = '10000'
    Protocol = 'All'
    IdleTimeoutInMinutes = '15'
    FrontendIPConfiguration = $lb.FrontendIpConfigurations[1]
    BackendAddressPool = $lb.BackendAddressPools[1]
}
$lb | Add-AzLoadBalancerOutBoundRuleConfig @rule | Set-AzLoadBalancer

將虛擬機器新增至輸出集區Add virtual machines to outbound pool

使用 Add-AzNetworkInterfaceIpConfig,將虛擬機器網路介面新增至負載平衡器的輸出集區:Add the virtual machine network interfaces to the outbound pool of the load balancer with Add-AzNetworkInterfaceIpConfig:

## Get the load balancer configuration ##
$lbc = @{
    ResourceGroupName = 'CreatePubLBQS-rg'
    Name = 'myLoadBalancer'
}
$lb = Get-AzLoadBalancer @lbc

# For loop with variable to add virtual machines to backend outbound pool. ##
for ($i=1; $i -le 3; $i++)
{
$nic = @{
    ResourceGroupName = 'CreatePubLBQS-rg'
    Name = "myNicVM$i"
}
$nicvm = Get-AzNetworkInterface @nic

## Apply the backend to the network interface ##
$be = @{
    Name = 'ipconfig1'
    LoadBalancerBackendAddressPoolId = $lb.BackendAddressPools[0].id,$lb.BackendAddressPools[1].id
}
$nicvm | Set-AzNetworkInterfaceIpConfig @be | Set-AzNetworkInterface
}

安裝 IISInstall IIS

使用 Set-AzVMExtension 來安裝自訂指令碼擴充功能。Use Set-AzVMExtension 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:

重要

請先確定您已完成先前步驟中的虛擬機器部署,再繼續操作。Ensure the virtual machine deployments have completed from the previous steps before proceeding. 請使用 Get-Job 檢查虛擬機器部署作業的狀態。Use Get-Job to check the status of the virtual machine deployment jobs.

## For loop with variable to install custom script extension on virtual machines. ##
for ($i=1; $i -le 3; $i++)
{
$ext = @{
    Publisher = 'Microsoft.Compute'
    ExtensionType = 'CustomScriptExtension'
    ExtensionName = 'IIS'
    ResourceGroupName = 'CreatePubLBQS-rg'
    VMName = "myVM$i"
    Location = 'eastus'
    TypeHandlerVersion = '1.8'
    SettingString = '{"commandToExecute":"powershell Add-WindowsFeature Web-Server; powershell Add-Content -Path \"C:\\inetpub\\wwwroot\\Default.htm\" -Value $($env:computername)"}'
}
Set-AzVMExtension @ext -AsJob
}

擴充功能會以 PowerShell 作業的形式部署。The extensions are deployed as PowerShell jobs. 若要檢視安裝作業的狀態,請使用 Get-JobTo view the status of the installation jobs, use Get-Job:

Get-Job

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
8      Long Running O… AzureLongRunni… Running       True            localhost            Set-AzVMExtension
9      Long Running O… AzureLongRunni… Running       True            localhost            Set-AzVMExtension
10     Long Running O… AzureLongRunni… Running       True            localhost            Set-AzVMExtension

測試負載平衡器Test the load balancer

使用 Get-AzPublicIpAddress 取得負載平衡器的公用 IP 位址:Use Get-AzPublicIpAddress to get the public IP address of the load balancer:

$ip = @{
    ResourceGroupName = 'CreatePubLBQS-rg'
    Name = 'myPublicIP'
}  
Get-AzPublicIPAddress @ip | select IpAddress

將公用 IP 位址複製並貼到您瀏覽器的網址列。Copy the public IP address, and then paste it into the address bar of your browser. IIS Web 伺服器的預設頁面會顯示在瀏覽器上。The default page of IIS Web server is displayed on the browser.

IIS Web 伺服器

若要讓負載平衡器將流量分散到這三個 VM,您可以為每個 VM 的 IIS Web 伺服器自訂預設頁面,然後從用戶端機器強制重新整理您的網頁瀏覽器。To see the load balancer distribute traffic across all three VMs, you can customize the default page of each VM's IIS Web server and then force-refresh your web browser from the client machine.

清除資源Clean up resources

當不再需要時,您可以使用 Remove-AzResourceGroup 命令來移除資源群組、負載平衡器和其餘資源。When no longer needed, you can use the Remove-AzResourceGroup command to remove the resource group, load balancer, and the remaining resources.

Remove-AzResourceGroup -Name 'CreatePubLBQS-rg'

後續步驟Next steps

在本快速入門中:In this quickstart:

  • 您建立了標準或基本公用負載平衡器You created a standard or basic public load balancer
  • 連結的虛擬機器。Attached virtual machines.
  • 設定了負載平衡器流量規則和健康情況探查。Configured the load balancer traffic rule and health probe.
  • 測試了負載平衡器。Tested the load balancer.

若要深入了解 Azure Load Balancer,請繼續:To learn more about Azure Load Balancer, continue to: