快速入門:使用 Azure PowerShell 來建立內部負載平衡器以平衡 VM 的負載

使用 Azure PowerShell 建立內部負載平衡器和兩部虛擬機器,來開始使用 Azure Load Balancer。其他資源包括 Azure Bastion、NAT 閘道、虛擬網路和所需的子網路。

針對內部負載平衡器部署的資源圖表。

必要條件

  • 具有有效訂用帳戶的 Azure 帳戶。 免費建立帳戶

  • 已在本機安裝 Azure PowerShell 或 Azure Cloud Shell

如果您選擇在本機安裝和使用 PowerShell,本文會要求使用 Azure PowerShell 模組版本 5.4.1 或更新版本。 執行 Get-Module -ListAvailable Az 以尋找安裝的版本。 如果您需要升級,請參閱安裝 Azure PowerShell 模組。 如果正在本機執行 PowerShell,也需要執行 Connect-AzAccount,以建立與 Azure 的連線。

建立資源群組

Azure 資源群組是在其中部署與管理 Azure 資源的邏輯容器。

使用 New-AzResourceGroup 來建立資源群組。

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

設定虛擬網路

當您建立內部負載平衡器時,會將虛擬網路設定為負載平衡器的網路。 請先建立支援的虛擬網路資源,才可部署 VM 並測試您的負載平衡器。

  • 建立 NAT 閘道的公用 IP

  • 建立後端虛擬機器的虛擬網路

  • 建立網路安全性群組,以定義虛擬網路的輸入連線

  • 建立 Azure Bastion 主機來安全在後端集區中管理虛擬機器

建立公用 IP 位址

使用 New-AzPublicIpAddress 建立 NAT 閘道的公用 IP 位址。

## Create public IP address for NAT gateway and place IP in variable ##
$gwpublicip = @{
    Name = 'myNATgatewayIP'
    ResourceGroupName = 'CreateIntLBQS-rg'
    Location = 'eastus'
    Sku = 'Standard'
    AllocationMethod = 'static'
    Zone = 1,2,3
}
$gwpublicip = New-AzPublicIpAddress @gwpublicip

若要在區域 1 中建立區域性公用 IP 位址,請使用下列命令:

## Create a zonal public IP address for NAT gateway and place IP in variable ##
$gwpublicip = @{
    Name = 'myNATgatewayIP'
    ResourceGroupName = 'CreateIntLBQS-rg'
    Location = 'eastus'
    Sku = 'Standard'
    AllocationMethod = 'static'
    Zone = 1
}
$gwpublicip = New-AzPublicIpAddress @gwpublicip

注意

NAT 閘道會使用公用 IP 位址,為後端集區中的虛擬機器提供輸出連線。 當您建立內部負載平衡器,並需要後端集區資源具有輸出連線時,建議您這麼做。 如需詳細資訊,請參閱 NAT 閘道

建立虛擬網路、網路安全性群組、堡壘主機和 NAT 閘道

重要

每小時定價從 Bastion 部署的那一刻開始,不論輸出資料使用量為何。 如需詳細資訊,請參閱價格SKU。 如果您要將 Bastion 部署為教學課程或測試的一部份,建議您在使用完畢後刪除此資源。


## Create NAT gateway resource ##
$nat = @{
    ResourceGroupName = 'CreateIntLBQS-rg'
    Name = 'myNATgateway'
    IdleTimeoutInMinutes = '10'
    Sku = 'Standard'
    Location = 'eastus'
    PublicIpAddress = $gwpublicip
}
$natGateway = New-AzNatGateway @nat

## Create backend subnet config ##
$subnet = @{
    Name = 'myBackendSubnet'
    AddressPrefix = '10.1.0.0/24'
    NatGateway = $natGateway
}
$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 = 'CreateIntLBQS-rg'
    Location = 'eastus'
    AddressPrefix = '10.1.0.0/16'
    Subnet = $subnetConfig,$bastsubnetConfig
}
$vnet = New-AzVirtualNetwork @net

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

## Create bastion host ##
$bastion = @{
    ResourceGroupName = 'CreateIntLBQS-rg'
    Name = 'myBastion'
    PublicIpAddress = $bastionip
    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 = 'CreateIntLBQS-rg'
    Location = 'eastus'
    SecurityRules = $rule1
}
New-AzNetworkSecurityGroup @nsg

建立負載平衡器

本節將詳細說明如何建立及設定下列負載平衡器元件:

## Place virtual network created in previous step into a variable. ##
$net = @{
    Name = 'myVNet'
    ResourceGroupName = 'CreateIntLBQS-rg'
}
$vnet = Get-AzVirtualNetwork @net

## Create load balancer frontend configuration and place in variable. ##
$lbip = @{
    Name = 'myFrontEnd'
    PrivateIpAddress = '10.1.0.4'
    SubnetId = $vnet.subnets[0].Id
}
$feip = New-AzLoadBalancerFrontendIpConfig @lbip

## 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 = 'tcp'
    Port = '80'
    IntervalInSeconds = '360'
    ProbeCount = '5'
}
$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

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

建立虛擬機器

在本節中,您會針對負載平衡器的後端集區建立兩部虛擬機器。

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

## Place virtual network created in previous step into a variable. ##
$net = @{
    Name = 'myVNet'
    ResourceGroupName = 'CreateIntLBQS-rg'
}
$vnet = Get-AzVirtualNetwork @net

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

## Place the network security group into a variable. ##
$sg = {
    Name = 'myNSG'
    ResourceGroupName = 'CreateIntLBQS-rg' @sg
}
$nsg = Get-AzNetworkSecurityGroup 

## For loop with variable to create virtual machines for load balancer backend pool. ##
for ($i=1; $i -le 2; $i++)
{
    ## Command to create network interface for VMs ##
    $nic = @{
    Name = "myNicVM$i"
    ResourceGroupName = 'CreateIntLBQS-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 = 'CreateIntLBQS-rg'
        Location = 'eastus'
        VM = $vmConfig
        Zone = "$i"
    }
}
New-AzVM @vm -asjob

虛擬機器和堡壘主機的部署會以 PowerShell 作業的形式提交。 若要檢視作業的狀態,請使用 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

注意

Azure 會針對未獲指派公用 IP 位址或位於內部基本 Azure 負載平衡器後端集區中的 VM,提供預設輸出存取 IP。 預設輸出存取 IP 機制能提供無法自行設定的輸出 IP 位址。

發生下列其中一個事件時,會停用預設輸出存取 IP:

  • 系統會指派公用 IP 位址給 VM。
  • 無論有沒有輸出規則,都會將 VM 放在標準負載平衡器的後端集區中。
  • Azure NAT 閘道資源會指派給 VM 的子網。

在彈性協調流程模式中使用虛擬機器擴展集建立的 VM 不會有預設輸出存取。

如需 Azure 中輸出連線的詳細資訊,請參閱 Azure 中的預設對外存取針對輸出連線,使用來源網路位址轉譯 (SNAT)

安裝 IIS

使用 Set-AzVMExtension 來安裝自訂指令碼擴充功能。

此延伸模組會執行 PowerShell Add-WindowsFeature Web-Server 以安裝 IIS Web 伺服器,然後更新 Default.htm 頁面以顯示 VM 的主機名稱:

重要

請先確定您已完成先前步驟中的虛擬機器部署,再繼續操作。 請使用 Get-Job 檢查虛擬機器部署作業的狀態。

## For loop with variable to install custom script extension on virtual machines. ##
for ($i=1; $i -le 2; $i++)
{
    $ext = @{
        Publisher = 'Microsoft.Compute'
        ExtensionType = 'CustomScriptExtension'
        ExtensionName = 'IIS'
        ResourceGroupName = 'CreateIntLBQS-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 作業的形式部署。 若要檢視安裝作業的狀態,請使用 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

建立測試虛擬機器

使用下列 Cmdlet 建立虛擬機器:

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

## Place the virtual network into a variable. ##
$net = @{
    Name = 'myVNet'
    ResourceGroupName = 'CreateIntLBQS-rg'
}
$vnet = Get-AzVirtualNetwork @net

## Place the network security group into a variable. ##
$sg = {
    Name = 'myNSG'
    ResourceGroupName = 'CreateIntLBQS-rg' @sg
}
$nsg = Get-AzNetworkSecurityGroup

## Command to create network interface for VM ##
$nic = @{
    Name = "myNicTestVM"
    ResourceGroupName = 'CreateIntLBQS-rg'
    Location = 'eastus'
    Subnet = $vnet.Subnets[0]
    NetworkSecurityGroup = $nsg
}
$nicVM = New-AzNetworkInterface @nic

## Create a virtual machine configuration for VMs ##
$vmsz = @{
    VMName = "myTestVM"
    VMSize = 'Standard_DS1_v2' 
}
$vmos = @{
    ComputerName = "myTestVM"
    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 = 'CreateIntLBQS-rg'
    Location = 'eastus'
    VM = $vmConfig
}
New-AzVM @vm

測試負載平衡器

  1. 登入 Azure 入口網站。

  2. 在 [概觀] 畫面上尋找負載平衡器的私人 IP 位址。 選取左側功能表中的 [所有服務]、選取 [所有資源],然後選取 [myLoadBalancer]

  3. myLoadBalancer概觀中,記下或複製私人 IP 位址 旁的位址。

  4. 選取左側功能表中的 [所有服務]、選取 [所有資源],然後從資源清單選取 CreateIntLBQS-rg 資源群組中的 [myTestVM]

  5. 在 [概觀] 頁面上,選取 [連線],然後選 [Bastion]。

  6. 輸入在 VM 建立期間輸入的使用者名稱和密碼。

  7. myTestVM 上開啟 Internet Explorer

  8. 在瀏覽器的網址列中,輸入上一個步驟中的 IP 位址。 自訂 IIS 網頁伺服器頁面隨即顯示。

    網頁瀏覽器的螢幕快照,其中顯示負載平衡 VM 的預設網頁

若要查看負載平衡器如何將流量分散於所有三部 VM,您可以從測試機器中強制重新整理您的網頁瀏覽器。

清除資源

當不再需要時,您可以使用 Remove-AzResourceGroup 命令來移除資源群組、負載平衡器和其餘資源。

Remove-AzResourceGroup -Name 'CreateIntLBQS-rg'

下一步

在本快速入門中:

  • 您已建立內部負載平衡器

  • 連結的虛擬機器

  • 已設定負載平衡器流量規則和健康情況探查

  • 測試了負載平衡器

若要深入了解 Azure Load Balancer,請繼續: