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

教程:在 Azure 中使用 Azure CLI 2.0 均衡 Linux 虚拟机负载以创建高可用性应用程序Tutorial: Load balance Linux virtual machines in Azure to create a highly available application with the Azure CLI 2.0

负载均衡通过将传入请求分布到多个虚拟机来提供更高级别的可用性。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
  • 使用 cloud-init 创建基本的 Node.js 应用Use cloud-init to create a basic Node.js app
  • 创建虚拟机并将其附加到负载均衡器Create virtual machines and attach to a load balancer
  • 查看运行中的负载均衡器View a load balancer in action
  • 从负载均衡器中添加和删除 VMAdd and remove VMs from a load balancer

打开 Azure Cloud ShellOpen Azure Cloud Shell

Azure Cloud Shell 是免费的交互式 shell,可以使用它运行本文中的步骤。Azure Cloud Shell is a free, interactive shell that you can use to run the steps in this article. Cloud Shell 中预安装并配置了常用 Azure 工具供你与帐户一起使用。Common Azure tools are preinstalled and configured in Cloud Shell for you to use with your account. 只需选择“复制”按钮即可复制代码,将其粘贴到 Cloud Shell 中,然后按 Enter 来运行它。Just select the Copy button to copy the code, paste it in Cloud Shell, and then press Enter to run it. 可通过多种方式打开 Cloud Shell:There are a few ways to open Cloud Shell:

选择代码块右上角的“试用”。Select Try It in the upper-right corner of a code block. 本文中的 Cloud Shell
在浏览器中打开 Cloud Shell。Open Cloud Shell in your browser. https://shell.azure.com/bash
选择 Azure 门户右上角菜单上的“Cloud Shell”按钮。Select the Cloud Shell button on the menu in the upper-right corner of the Azure portal. 门户中的 Cloud Shell

如果选择在本地安装并使用 CLI,本教程要求运行 Azure CLI 2.0.30 或更高版本。If you choose to install and use the CLI locally, this tutorial requires that you are running the Azure CLI version 2.0.30 or later. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要进行安装或升级,请参阅安装 Azure CLI 2.0If you need to install or upgrade, see Install Azure CLI 2.0.

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.

如果遵循了前面的教程来创建虚拟机规模集,则已创建负载均衡器。If you followed the previous tutorial to create a virtual machine scale set, a load balancer was created for you. 所有这些组件都已配置为规模集的一部分。All these components were configured for you as part of the scale set.

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

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

az group create --name 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. 使用 az network public-ip create 创建公共 IP 地址。Create a public IP address with az network public-ip create. 以下示例在“myResourceGroupLoadBalancer”资源组中创建名为“myPublicIP”的公共 IP 地址:The following example creates a public IP address named myPublicIP in the myResourceGroupLoadBalancer resource group:

az network public-ip create \
    --resource-group myResourceGroupLoadBalancer \
    --name myPublicIP

创建负载均衡器Create a load balancer

使用 az network lb create 创建负载均衡器。Create a load balancer with az network lb create. 以下示例创建名为“myLoadBalancer”的负载均衡器,并将“myPublicIP”地址分配到前端 IP 配置:The following example creates a load balancer named myLoadBalancer and assigns the myPublicIP address to the front-end IP configuration:

az network lb create \
    --resource-group myResourceGroupLoadBalancer \
    --name myLoadBalancer \
    --frontend-ip-name myFrontEndPool \
    --backend-pool-name myBackEndPool \
    --public-ip-address myPublicIP

创建运行状况探测器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.js。When using a custom HTTP probe, you must create the health check page, such as healthcheck.js. 探测必须为负载均衡器返回 HTTP 200 OK 响应,以保持主机处于旋转状态。The probe must return an HTTP 200 OK response for the load balancer to keep the host in rotation.

若要创建 TCP 运行状况探测,请使用 az network lb probe createTo create a TCP health probe, you use az network lb probe create. 以下示例创建名为“myHealthProbe”的运行状况探测:The following example creates a health probe named myHealthProbe:

az network lb probe create \
    --resource-group myResourceGroupLoadBalancer \
    --lb-name myLoadBalancer \
    --name myHealthProbe \
    --protocol tcp \
    --port 80

创建负载均衡器规则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.

使用 az network lb rule create 创建负载均衡器规则。Create a load balancer rule with az network lb rule create. 以下示例创建名为“myLoadBalancerRule”的规则、使用“myHealthProbe”运行状况探测并平衡端口 80 上的流量:The following example creates a rule named myLoadBalancerRule, uses the myHealthProbe health probe, and balances traffic on port 80:

az network lb rule create \
    --resource-group myResourceGroupLoadBalancer \
    --lb-name myLoadBalancer \
    --name myLoadBalancerRule \
    --protocol tcp \
    --frontend-port 80 \
    --backend-port 80 \
    --frontend-ip-name myFrontEndPool \
    --backend-pool-name myBackEndPool \
    --probe-name myHealthProbe

配置虚拟网络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

使用 az network vnet create 创建虚拟网络。Create a virtual network with az network vnet create. 以下示例创建名为“myVnet”的虚拟网络和一个名为“mySubnet”的子网:The following example creates a virtual network named myVnet with a subnet named mySubnet:

az network vnet create \
    --resource-group myResourceGroupLoadBalancer \
    --name myVnet \
    --subnet-name mySubnet

若要添加网络安全组,请使用 az network nsg createTo add a network security group, you use az network nsg create. 以下示例创建名为“myNetworkSecurityGroup”的网络安全组:The following example creates a network security group named myNetworkSecurityGroup:

az network nsg create \
    --resource-group myResourceGroupLoadBalancer \
    --name myNetworkSecurityGroup

使用 az network nsg rule create 创建网络安全组规则。Create a network security group rule with az network nsg rule create. 以下示例创建名为“myNetworkSecurityGroupRule”的网络安全组规则:The following example creates a network security group rule named myNetworkSecurityGroupRule:

az network nsg rule create \
    --resource-group myResourceGroupLoadBalancer \
    --nsg-name myNetworkSecurityGroup \
    --name myNetworkSecurityGroupRule \
    --priority 1001 \
    --protocol tcp \
    --destination-port-range 80

使用 az network nic create 创建虚拟 NIC。Virtual NICs are created with az network nic create. 以下示例创建三个虚拟 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 in `seq 1 3`; do
    az network nic create \
        --resource-group myResourceGroupLoadBalancer \
        --name myNic$i \
        --vnet-name myVnet \
        --subnet mySubnet \
        --network-security-group myNetworkSecurityGroup \
        --lb-name myLoadBalancer \
        --lb-address-pools myBackEndPool
done

创建所有三个虚拟 NIC 之后,请继续执行下一步骤When all three virtual NICs are created, continue on to the next step

创建虚拟机Create virtual machines

创建 cloud-init 配置Create cloud-init config

在有关如何在首次启动时自定义 Linux 虚拟机的上一个教程中,已了解如何使用 cloud-init 自动执行 VM 自定义。In a previous tutorial on How to customize a Linux virtual machine on first boot, you learned how to automate VM customization with cloud-init. 在下一步骤中,可使用同一个 cloud-init 配置文件安装 NGINX 并运行简单的“Hello World”Node.js 应用。You can use the same cloud-init configuration file to install NGINX and run a simple 'Hello World' Node.js app in the next step. 若要查看负载均衡器的工作方式,完成本教程时,可以在 Web 浏览器中访问这个简单的应用。To see the load balancer in action, at the end of the tutorial you access this simple app in a web browser.

在当前 shell 中,创建名为“cloud-init.txt”的文件并粘贴下面的配置。In your current shell, create a file named cloud-init.txt and paste the following configuration. 例如,在不处于本地计算机上的 Cloud Shell 中创建文件。For example, create the file in the Cloud Shell not on your local machine. 输入 sensible-editor cloud-init.txt 以创建文件并查看可用编辑器的列表。Enter sensible-editor cloud-init.txt to create the file and see a list of available editors. 请确保已正确复制整个 cloud-init 文件,尤其是第一行:Make sure that the whole cloud-init file is copied correctly, especially the first line:

#cloud-config
package_upgrade: true
packages:
  - nginx
  - nodejs
  - npm
write_files:
  - owner: www-data:www-data
  - path: /etc/nginx/sites-available/default
    content: |
      server {
        listen 80;
        location / {
          proxy_pass http://localhost:3000;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection keep-alive;
          proxy_set_header Host $host;
          proxy_cache_bypass $http_upgrade;
        }
      }
  - owner: azureuser:azureuser
  - path: /home/azureuser/myapp/index.js
    content: |
      var express = require('express')
      var app = express()
      var os = require('os');
      app.get('/', function (req, res) {
        res.send('Hello World from host ' + os.hostname() + '!')
      })
      app.listen(3000, function () {
        console.log('Hello world app listening on port 3000!')
      })
runcmd:
  - service nginx restart
  - cd "/home/azureuser/myapp"
  - npm init
  - npm install express -y
  - nodejs index.js

创建虚拟机Create virtual machines

要提高应用的高可用性,请将 VM 放置在可用性集中。To improve the high availability of your app, place your VMs in an availability set. 有关可用性集的详细信息,请参阅前面的如何创建高可用性虚拟机教程。For more information about availability sets, see the previous How to create highly available virtual machines tutorial.

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

az vm availability-set create \
    --resource-group myResourceGroupLoadBalancer \
    --name myAvailabilitySet

现在,可使用 az vm create 创建 VM。Now you can create the VMs with az vm create. 以下示例创建三个 VM,并生成 SSH 密钥(如果它们尚不存在):The following example creates three VMs and generates SSH keys if they do not already exist:

for i in `seq 1 3`; do
    az vm create \
        --resource-group myResourceGroupLoadBalancer \
        --name myVM$i \
        --availability-set myAvailabilitySet \
        --nics myNic$i \
        --image UbuntuLTS \
        --admin-username azureuser \
        --generate-ssh-keys \
        --custom-data cloud-init.txt \
        --no-wait
done

在 Azure CLI 向你返回提示之后,仍然存在继续运行的后台任务。There are background tasks that continue to run after the Azure CLI returns you to the prompt. --no-wait 参数不会等待所有任务完成。The --no-wait parameter does not wait for all the tasks to complete. 可能还需等待几分钟才能访问应用。It may be another couple of minutes before you can access the app. 在每个 VM 上运行应用时,负载均衡器运行状况探测器会自动检测。The load balancer health probe automatically detects when the app is running on each VM. 应用运行后,负载均衡器规则将开始分布流量。Once the app is running, the load balancer rule starts to distribute traffic.

测试负载均衡器Test load balancer

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

az network public-ip show \
    --resource-group myResourceGroupLoadBalancer \
    --name myPublicIP \
    --query [ipAddress] \
    --output tsv

然后,可将公共 IP 地址输入 web 浏览器中。You can then enter the public IP address in to a web browser. 请记住 - 在负载均衡器开始向 VM 分发流量之前,VM 需要几分钟才能准备就绪。Remember - it takes a few minutes for the VMs to be ready before the load balancer starts to distribute traffic to them. 随即显示应用,包括负载均衡器将流量分发到的 VM 的主机名,如下例所示:The app is displayed, including the hostname of the VM that the load balancer distributed traffic to as in the following example:

运行 Node.js 应用

若要查看负载均衡器如何在运行应用的所有 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

可使用 az network nic ip-config address-pool remove 从后端地址池中删除 VM。You can remove a VM from the backend address pool with az network nic ip-config address-pool remove. 以下示例从“myLoadBalancer”中删除“myVM2”的虚拟 NIC:The following example removes the virtual NIC for myVM2 from myLoadBalancer:

az network nic ip-config address-pool remove \
    --resource-group myResourceGroupLoadBalancer \
    --nic-name myNic2 \
    --ip-config-name ipConfig1 \
    --lb-name myLoadBalancer \
    --address-pool myBackEndPool 

若要查看负载均衡器如何在运行应用的其余两个 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.

若要查看包含与负载均衡器连接的虚拟 NIC 的 VM 列表,请使用 az network lb address-pool showTo view a list of VMs with virtual NICs connected to the load balancer, use az network lb address-pool show. 如下所示根据虚拟 NIC 的 ID 进行查询和筛选:Query and filter on the ID of the virtual NIC as follows:

az network lb address-pool show \
    --resource-group myResourceGroupLoadBalancer \
    --lb-name myLoadBalancer \
    --name myBackEndPool \
    --query backendIpConfigurations \
    --output tsv | cut -f4

输出类似于以下示例,其中显示 VM 2 的虚拟 NIC 不再是后端地址池的一部分:The output is similar to the following example, which shows that the virtual NIC for VM 2 is no longer part of the backend address pool:

/subscriptions/<guid>/resourceGroups/myResourceGroupLoadBalancer/providers/Microsoft.Network/networkInterfaces/myNic1/ipConfigurations/ipconfig1
/subscriptions/<guid>/resourceGroups/myResourceGroupLoadBalancer/providers/Microsoft.Network/networkInterfaces/myNic3/ipConfigurations/ipconfig1

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

执行 VM 维护后,或者如果需要扩展容量,可使用 az network nic ip-config address-pool add 将 VM 添加到后端地址池。After performing VM maintenance, or if you need to expand capacity, you can add a VM to the backend address pool with az network nic ip-config address-pool add. 以下示例将“myVM2”的虚拟 NIC 添加到“myLoadBalancer”:The following example adds the virtual NIC for myVM2 to myLoadBalancer:

az network nic ip-config address-pool add \
    --resource-group myResourceGroupLoadBalancer \
    --nic-name myNic2 \
    --ip-config-name ipConfig1 \
    --lb-name myLoadBalancer \
    --address-pool myBackEndPool

若要验证虚拟 NIC 是否已连接到后端地址池,请再次使用上一步骤中所示的 az network lb address-pool showTo verify that the virtual NIC is connected to the backend address pool, use az network lb address-pool show again from the preceding step.

后续步骤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
  • 使用 cloud-init 创建基本的 Node.js 应用Use cloud-init to create a basic Node.js app
  • 创建虚拟机并将其附加到负载均衡器Create virtual machines and attach to a load balancer
  • 查看运行中的负载均衡器View a load balancer in action
  • 从负载均衡器中添加和删除 VMAdd and remove VMs from a load balancer

请转到下一教程,深入了解 Azure 虚拟网络组件。Advance to the next tutorial to learn more about Azure virtual network components.