你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:使用 ARM 模板创建公共负载均衡器,以对 VM 进行负载均衡

负载均衡将传入请求分布到多个虚拟机 (VM),从而提供更高级别的可用性和可伸缩性。

本快速入门演示如何部署标准负载均衡器,以对虚拟机进行负载均衡。

为标准公共负载均衡器部署的资源示意图。

与其他部署方法相比,使用 ARM 模板需要的步骤更少。

Azure 资源管理器模板是定义项目基础结构和配置的 JavaScript 对象表示法 (JSON) 文件。 模板使用声明性语法。 你可以在不编写用于创建部署的编程命令序列的情况下,描述预期部署。

如果你的环境满足先决条件,并且你熟悉如何使用 ARM 模板,请选择“部署到 Azure”按钮。 Azure 门户中会打开模板。

用于将资源管理器模板部署到 Azure 的按钮。

先决条件

如果没有 Azure 订阅,请在开始之前创建一个免费帐户

查看模板

本快速入门中使用的模板来自 Azure 快速启动模板

负载均衡器和公共 IP SKU 必须匹配。 创建标准负载均衡器时,还必须创建一个作为该标准负载均衡器的前端配置的新标准公共 IP 地址。 若要创建基本负载均衡器,请使用此模板。 Microsoft 建议将标准 SKU 用于生产工作负载。

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.26.54.24096",
      "templateHash": "14680538243429534307"
    }
  },
  "parameters": {
    "projectName": {
      "type": "string",
      "metadata": {
        "description": "Specifies a project name that is used for generating resource names."
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "Specifies the location for all of the resources created by this template."
      }
    },
    "adminUsername": {
      "type": "string",
      "metadata": {
        "description": "Specifies the virtual machine administrator username."
      }
    },
    "adminPassword": {
      "type": "securestring",
      "metadata": {
        "description": "Specifies the virtual machine administrator password."
      }
    },
    "vmSize": {
      "type": "string",
      "defaultValue": "Standard_D2s_v3",
      "metadata": {
        "description": "Size of the virtual machine"
      }
    },
    "OSVersion": {
      "type": "string",
      "defaultValue": "2022-datacenter-azure-edition",
      "allowedValues": [
        "2016-datacenter-gensecond",
        "2016-datacenter-server-core-g2",
        "2016-datacenter-server-core-smalldisk-g2",
        "2016-datacenter-smalldisk-g2",
        "2016-datacenter-with-containers-g2",
        "2016-datacenter-zhcn-g2",
        "2019-datacenter-core-g2",
        "2019-datacenter-core-smalldisk-g2",
        "2019-datacenter-core-with-containers-g2",
        "2019-datacenter-core-with-containers-smalldisk-g2",
        "2019-datacenter-gensecond",
        "2019-datacenter-smalldisk-g2",
        "2019-datacenter-with-containers-g2",
        "2019-datacenter-with-containers-smalldisk-g2",
        "2019-datacenter-zhcn-g2",
        "2022-datacenter-azure-edition",
        "2022-datacenter-azure-edition-core",
        "2022-datacenter-azure-edition-core-smalldisk",
        "2022-datacenter-azure-edition-smalldisk",
        "2022-datacenter-core-g2",
        "2022-datacenter-core-smalldisk-g2",
        "2022-datacenter-g2",
        "2022-datacenter-smalldisk-g2"
      ],
      "metadata": {
        "description": "The Windows version for the VM. This will pick a fully patched image of this given Windows version."
      }
    },
    "imageSku": {
      "type": "string",
      "defaultValue": "vs-2019-ent-latest-win11-n-gen2",
      "allowedValues": [
        "vs-2019-ent-latest-win11-n-gen2",
        "vs-2019-pro-general-win11-m365-gen2",
        "vs-2019-comm-latest-win11-n-gen2",
        "vs-2019-ent-general-win10-m365-gen2",
        "vs-2019-ent-general-win11-m365-gen2",
        "vs-2019-pro-general-win10-m365-gen2"
      ],
      "metadata": {
        "description": "Linux Sku"
      }
    },
    "securityType": {
      "type": "string",
      "defaultValue": "TrustedLaunch",
      "allowedValues": [
        "Standard",
        "TrustedLaunch"
      ],
      "metadata": {
        "description": "Security Type of the Virtual Machine."
      }
    }
  },
  "variables": {
    "securityProfileJson": {
      "uefiSettings": {
        "secureBootEnabled": true,
        "vTpmEnabled": true
      },
      "securityType": "[parameters('securityType')]"
    },
    "lbName": "[format('{0}-lb', parameters('projectName'))]",
    "lbSkuName": "Standard",
    "lbPublicIpAddressName": "[format('{0}-lbPublicIP', parameters('projectName'))]",
    "lbFrontEndName": "LoadBalancerFrontEnd",
    "lbBackendPoolName": "LoadBalancerBackEndPool",
    "lbProbeName": "loadBalancerHealthProbe",
    "nsgName": "[format('{0}-nsg', parameters('projectName'))]",
    "vNetName": "[format('{0}-vnet', parameters('projectName'))]",
    "vNetAddressPrefix": "10.0.0.0/16",
    "vNetSubnetName": "BackendSubnet",
    "vNetSubnetAddressPrefix": "10.0.0.0/24",
    "bastionName": "[format('{0}-bastion', parameters('projectName'))]",
    "bastionSubnetName": "AzureBastionSubnet",
    "vNetBastionSubnetAddressPrefix": "10.0.1.0/24",
    "bastionPublicIPAddressName": "[format('{0}-bastionPublicIP', parameters('projectName'))]",
    "vmStorageAccountType": "Premium_LRS",
    "extensionName": "GuestAttestation",
    "extensionPublisher": "Microsoft.Azure.Security.WindowsAttestation",
    "extensionVersion": "1.0",
    "maaTenantName": "GuestAttestation",
    "maaEndpoint": "[substring('emptyString', 0, 0)]",
    "ascReportingEndpoint": "[substring('emptystring', 0, 0)]",
    "natGatewayName": "[format('{0}-natgateway', parameters('projectName'))]",
    "natGatewayPublicIPAddressName": "[format('{0}-natPublicIP', parameters('projectName'))]"
  },
  "resources": [
    {
      "copy": {
        "name": "project_vm_1_networkInterface",
        "count": "[length(range(0, 3))]"
      },
      "type": "Microsoft.Network/networkInterfaces",
      "apiVersion": "2021-08-01",
      "name": "[format('{0}-vm{1}-networkInterface', parameters('projectName'), add(range(0, 3)[copyIndex()], 1))]",
      "location": "[parameters('location')]",
      "properties": {
        "ipConfigurations": [
          {
            "name": "ipconfig1",
            "properties": {
              "privateIPAllocationMethod": "Dynamic",
              "subnet": {
                "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('vNetSubnetName'))]"
              },
              "loadBalancerBackendAddressPools": [
                {
                  "id": "[resourceId('Microsoft.Network/loadBalancers/backendAddressPools', variables('lbName'), variables('lbBackendPoolName'))]"
                }
              ]
            }
          }
        ],
        "networkSecurityGroup": {
          "id": "[resourceId('Microsoft.Network/networkSecurityGroups', variables('nsgName'))]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/loadBalancers', variables('lbName'))]",
        "[resourceId('Microsoft.Network/networkSecurityGroups', variables('nsgName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('vNetSubnetName'))]"
      ]
    },
    {
      "copy": {
        "name": "project_vm_1_InstallWebServer",
        "count": "[length(range(0, 3))]"
      },
      "type": "Microsoft.Compute/virtualMachines/extensions",
      "apiVersion": "2021-11-01",
      "name": "[format('{0}-vm{1}/InstallWebServer', parameters('projectName'), add(range(0, 3)[copyIndex()], 1))]",
      "location": "[parameters('location')]",
      "properties": {
        "publisher": "Microsoft.Compute",
        "type": "CustomScriptExtension",
        "typeHandlerVersion": "1.10",
        "autoUpgradeMinorVersion": true,
        "settings": {
          "commandToExecute": "powershell.exe Install-WindowsFeature -name Web-Server -IncludeManagementTools && powershell.exe remove-item 'C:\\inetpub\\wwwroot\\iisstart.htm' && powershell.exe Add-Content -Path 'C:\\inetpub\\wwwroot\\iisstart.htm' -Value $('Hello World from ' + $env:computername)"
        }
      },
      "dependsOn": [
        "project_vm_1"
      ]
    },
    {
      "copy": {
        "name": "project_vm_1",
        "count": "[length(range(1, 3))]"
      },
      "type": "Microsoft.Compute/virtualMachines",
      "apiVersion": "2021-11-01",
      "name": "[format('{0}-vm{1}', parameters('projectName'), range(1, 3)[copyIndex()])]",
      "location": "[parameters('location')]",
      "zones": [
        "[string(range(1, 3)[copyIndex()])]"
      ],
      "properties": {
        "hardwareProfile": {
          "vmSize": "[parameters('vmSize')]"
        },
        "storageProfile": {
          "imageReference": {
            "publisher": "MicrosoftWindowsServer",
            "offer": "WindowsServer",
            "sku": "[parameters('OSVersion')]",
            "version": "latest"
          },
          "osDisk": {
            "createOption": "FromImage",
            "managedDisk": {
              "storageAccountType": "[variables('vmStorageAccountType')]"
            }
          }
        },
        "networkProfile": {
          "networkInterfaces": [
            {
              "id": "[resourceId('Microsoft.Network/networkInterfaces', format('{0}-vm{1}-networkInterface', parameters('projectName'), range(1, 3)[copyIndex()]))]"
            }
          ]
        },
        "osProfile": {
          "computerName": "[format('{0}-vm{1}', parameters('projectName'), range(1, 3)[copyIndex()])]",
          "adminUsername": "[parameters('adminUsername')]",
          "adminPassword": "[parameters('adminPassword')]",
          "windowsConfiguration": {
            "enableAutomaticUpdates": true,
            "provisionVMAgent": true
          }
        },
        "securityProfile": "[if(equals(parameters('securityType'), 'TrustedLaunch'), variables('securityProfileJson'), null())]"
      },
      "dependsOn": [
        "project_vm_1_networkInterface"
      ]
    },
    {
      "copy": {
        "name": "projectName_vm_1_3_GuestAttestation",
        "count": "[length(range(1, 3))]"
      },
      "condition": "[and(equals(parameters('securityType'), 'TrustedLaunch'), and(equals(variables('securityProfileJson').uefiSettings.secureBootEnabled, true()), equals(variables('securityProfileJson').uefiSettings.vTpmEnabled, true())))]",
      "type": "Microsoft.Compute/virtualMachines/extensions",
      "apiVersion": "2022-03-01",
      "name": "[format('{0}-vm{1}/GuestAttestation', parameters('projectName'), range(1, 3)[copyIndex()])]",
      "location": "[parameters('location')]",
      "properties": {
        "publisher": "[variables('extensionPublisher')]",
        "type": "[variables('extensionName')]",
        "typeHandlerVersion": "[variables('extensionVersion')]",
        "autoUpgradeMinorVersion": true,
        "enableAutomaticUpgrade": true,
        "settings": {
          "AttestationConfig": {
            "MaaSettings": {
              "maaEndpoint": "[variables('maaEndpoint')]",
              "maaTenantName": "[variables('maaTenantName')]"
            },
            "AscSettings": {
              "ascReportingEndpoint": "[variables('ascReportingEndpoint')]",
              "ascReportingFrequency": ""
            },
            "useCustomToken": "false",
            "disableAlerts": "false"
          }
        }
      },
      "dependsOn": [
        "project_vm_1"
      ]
    },
    {
      "type": "Microsoft.Network/natGateways",
      "apiVersion": "2021-05-01",
      "name": "[variables('natGatewayName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard"
      },
      "properties": {
        "idleTimeoutInMinutes": 4,
        "publicIpAddresses": [
          {
            "id": "[resourceId('Microsoft.Network/publicIPAddresses', variables('natGatewayPublicIPAddressName'))]"
          }
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/publicIPAddresses', variables('natGatewayPublicIPAddressName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/publicIPAddresses",
      "apiVersion": "2021-05-01",
      "name": "[variables('natGatewayPublicIPAddressName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard"
      },
      "properties": {
        "publicIPAddressVersion": "IPv4",
        "publicIPAllocationMethod": "Static",
        "idleTimeoutInMinutes": 4
      }
    },
    {
      "type": "Microsoft.Network/virtualNetworks/subnets",
      "apiVersion": "2021-08-01",
      "name": "[format('{0}/{1}', variables('vNetName'), variables('bastionSubnetName'))]",
      "properties": {
        "addressPrefix": "[variables('vNetBastionSubnetAddressPrefix')]"
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/virtualNetworks', variables('vNetName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('vNetSubnetName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/virtualNetworks/subnets",
      "apiVersion": "2021-08-01",
      "name": "[format('{0}/{1}', variables('vNetName'), variables('vNetSubnetName'))]",
      "properties": {
        "addressPrefix": "[variables('vNetSubnetAddressPrefix')]",
        "natGateway": {
          "id": "[resourceId('Microsoft.Network/natGateways', variables('natGatewayName'))]"
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/natGateways', variables('natGatewayName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks', variables('vNetName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/bastionHosts",
      "apiVersion": "2021-08-01",
      "name": "[variables('bastionName')]",
      "location": "[parameters('location')]",
      "properties": {
        "ipConfigurations": [
          {
            "name": "IpConf",
            "properties": {
              "privateIPAllocationMethod": "Dynamic",
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses', variables('bastionPublicIPAddressName'))]"
              },
              "subnet": {
                "id": "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('bastionSubnetName'))]"
              }
            }
          }
        ]
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/publicIPAddresses', variables('bastionPublicIPAddressName'))]",
        "[resourceId('Microsoft.Network/virtualNetworks/subnets', variables('vNetName'), variables('bastionSubnetName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/publicIPAddresses",
      "apiVersion": "2021-08-01",
      "name": "[variables('bastionPublicIPAddressName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "[variables('lbSkuName')]"
      },
      "properties": {
        "publicIPAddressVersion": "IPv4",
        "publicIPAllocationMethod": "Static"
      }
    },
    {
      "type": "Microsoft.Network/loadBalancers",
      "apiVersion": "2021-08-01",
      "name": "[variables('lbName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "[variables('lbSkuName')]"
      },
      "properties": {
        "frontendIPConfigurations": [
          {
            "name": "[variables('lbFrontEndName')]",
            "properties": {
              "publicIPAddress": {
                "id": "[resourceId('Microsoft.Network/publicIPAddresses', variables('lbPublicIpAddressName'))]"
              }
            }
          }
        ],
        "backendAddressPools": [
          {
            "name": "[variables('lbBackendPoolName')]"
          }
        ],
        "loadBalancingRules": [
          {
            "name": "myHTTPRule",
            "properties": {
              "frontendIPConfiguration": {
                "id": "[resourceId('Microsoft.Network/loadBalancers/frontendIPConfigurations', variables('lbName'), variables('lbFrontEndName'))]"
              },
              "backendAddressPool": {
                "id": "[resourceId('Microsoft.Network/loadBalancers/backendAddressPools', variables('lbName'), variables('lbBackendPoolName'))]"
              },
              "frontendPort": 80,
              "backendPort": 80,
              "enableFloatingIP": false,
              "idleTimeoutInMinutes": 15,
              "protocol": "Tcp",
              "enableTcpReset": true,
              "loadDistribution": "Default",
              "disableOutboundSnat": true,
              "probe": {
                "id": "[resourceId('Microsoft.Network/loadBalancers/probes', variables('lbName'), variables('lbProbeName'))]"
              }
            }
          }
        ],
        "probes": [
          {
            "name": "[variables('lbProbeName')]",
            "properties": {
              "protocol": "Tcp",
              "port": 80,
              "intervalInSeconds": 5,
              "numberOfProbes": 2
            }
          }
        ],
        "outboundRules": []
      },
      "dependsOn": [
        "[resourceId('Microsoft.Network/publicIPAddresses', variables('lbPublicIpAddressName'))]"
      ]
    },
    {
      "type": "Microsoft.Network/publicIPAddresses",
      "apiVersion": "2021-08-01",
      "name": "[variables('lbPublicIpAddressName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "[variables('lbSkuName')]"
      },
      "properties": {
        "publicIPAddressVersion": "IPv4",
        "publicIPAllocationMethod": "Static"
      }
    },
    {
      "type": "Microsoft.Network/networkSecurityGroups",
      "apiVersion": "2021-08-01",
      "name": "[variables('nsgName')]",
      "location": "[parameters('location')]",
      "properties": {
        "securityRules": [
          {
            "name": "AllowHTTPInbound",
            "properties": {
              "protocol": "*",
              "sourcePortRange": "*",
              "destinationPortRange": "80",
              "sourceAddressPrefix": "Internet",
              "destinationAddressPrefix": "*",
              "access": "Allow",
              "priority": 100,
              "direction": "Inbound"
            }
          }
        ]
      }
    },
    {
      "type": "Microsoft.Network/virtualNetworks",
      "apiVersion": "2021-08-01",
      "name": "[variables('vNetName')]",
      "location": "[parameters('location')]",
      "properties": {
        "addressSpace": {
          "addressPrefixes": [
            "[variables('vNetAddressPrefix')]"
          ]
        }
      }
    }
  ],
  "outputs": {
    "location": {
      "type": "string",
      "value": "[parameters('location')]"
    },
    "name": {
      "type": "string",
      "value": "[variables('lbName')]"
    },
    "resourceGroupName": {
      "type": "string",
      "value": "[resourceGroup().name]"
    },
    "resourceId": {
      "type": "string",
      "value": "[resourceId('Microsoft.Network/loadBalancers', variables('lbName'))]"
    }
  }
}

该模板中已定义了多个 Azure 资源:

重要

小时定价从部署 Bastion 的时刻开始计算,而无论出站数据使用情况如何。 有关详细信息,请参阅定价SKU。 如果要将 Bastion 部署为教程或测试的一部分,建议在使用完此资源后将其删除。

若要查找与 Azure 负载均衡器相关的更多模板,请参阅 Azure 快速入门模板

部署模板

  1. 从以下代码块中选择“试用”,以打开 Azure Cloud Shell,然后按照相关说明登录到 Azure

    $projectName = Read-Host -Prompt "Enter a project name with 12 or less letters or numbers that is used to generate Azure resource names"
    $location = Read-Host -Prompt "Enter the location (i.e. centralus)"
    $adminUserName = Read-Host -Prompt "Enter the virtual machine administrator account name"
    $adminPassword = Read-Host -Prompt "Enter the virtual machine administrator password" -AsSecureString
    
    $resourceGroupName = "${projectName}rg"
    $templateUri = "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/quickstarts/microsoft.network/load-balancer-standard-create/azuredeploy.json"
    
    New-AzResourceGroup -Name $resourceGroupName -Location $location
    New-AzResourceGroupDeployment -ResourceGroupName $resourceGroupName -TemplateUri $templateUri -projectName $projectName -location $location -adminUsername $adminUsername -adminPassword $adminPassword
    
    Write-Host "Press [ENTER] to continue."
    

    等到控制台中显示提示。

  2. 从上一个代码块中选择“复制”,以复制 PowerShell 脚本。

  3. 右键单击 shell 控制台窗格,然后选择“粘贴”

  4. 输入相应的值。

    模板部署会创建三个可用性区域。 可用性区域仅在某些地区受到支持。 请使用受支持的地区之一。 如果不确定,请输入 centralus

    资源组名称是追加了 rg 的项目名称。 在下一部分中将用到资源组名称。

部署模板大约需要 10 分钟的时间。 完成后,输出类似于:

Azure 标准负载均衡器资源管理器模板 PowerShell 部署输出

使用 Azure PowerShell 部署模板。 还可以使用 Azure 门户、Azure CLI 和 REST API。 若要了解其他部署方法,请参阅部署模板

查看已部署的资源

  1. 登录 Azure 门户

  2. 从左侧窗格中选择“资源组”。

  3. 选择你在上一部分中创建的资源组。 默认资源组名称是追加了 -rg 的项目名称。

  4. 选择负载均衡器。 其默认名称是追加了 -lb 的项目名称。

  5. 仅复制公共 IP 地址的 IP 地址部分,然后将其粘贴到浏览器的地址栏中。

    Azure 标准负载均衡器资源管理器模板公共 IP

    浏览器将显示 Internet Information Services (IIS) Web 服务器的默认页。

    IIS Web 服务器

若要查看负载均衡器如何在所有 3 个 VM 之间分配流量,可从客户端计算机强制刷新 Web 浏览器。

清理资源

不再需要它们时,请删除:

  • 资源组
  • 负载均衡器
  • 相关资源

请访问 Azure 门户,选择包含负载均衡器的资源组,然后选择“删除资源组”。

后续步骤

在本快速入门中,请执行以下操作:

  • 为负载均衡器和虚拟机创建了虚拟网络。
  • 创建了用于管理的 Azure Bastion 主机。
  • 已创建标准负载均衡器并已将 VM 附加到它。
  • 配置了负载均衡器流量规则和运行状况探测。
  • 测试了负载均衡器。

若要了解详细信息,请继续学习与 Azure 负载均衡器相关的教程。