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

教程:使用 Azure CLI 2.0 在 Linux 上创建虚拟机规模集和部署高度可用的应用Tutorial: Create a virtual machine scale set and deploy a highly available app on Linux with the Azure CLI 2.0

利用虚拟机规模集,可以部署和管理一组相同的、自动缩放的虚拟机。A virtual machine scale set allows you to deploy and manage a set of identical, auto-scaling virtual machines. 可以手动缩放规模集中的 VM 数,也可以定义规则,以便根据资源使用情况(如 CPU 使用率、内存需求或网络流量)进行自动缩放。You can scale the number of VMs in the scale set manually, or define rules to autoscale based on resource usage such as CPU, memory demand, or network traffic. 在本教程中,会在 Azure 中部署虚拟机规模集。In this tutorial, you deploy a virtual machine scale set in Azure. 学习如何:You learn how to:

  • 使用 cloud-init 创建用于缩放的应用Use cloud-init to create an app to scale
  • 创建虚拟机规模集Create a virtual machine scale set
  • 增加或减少规模集中的实例数Increase or decrease the number of instances in a scale set
  • 创建自动缩放规则Create autoscale rules
  • 查看规模集实例的连接信息View connection info for scale set instances
  • 在规模集中使用数据磁盘Use data disks in a scale set

打开 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.

规模集概述Scale Set overview

利用虚拟机规模集,可以部署和管理一组相同的、自动缩放的虚拟机。A virtual machine scale set allows you to deploy and manage a set of identical, auto-scaling virtual machines. 规模集中的 VM 将分布在逻辑容错域和更新域的一个或多个放置组中。VMs in a scale set are distributed across logic fault and update domains in one or more placement groups. 这些放置组由配置类似的 VM 组成,与可用性集相似。These are groups of similarly configured VMs, similar to availability sets.

可以根据需要在规模集中创建 VM。VMs are created as needed in a scale set. 定义自动缩放规则,以控制如何以及何时在规模集中添加或删除 VM。You define autoscale rules to control how and when VMs are added or removed from the scale set. 这些规则基于 CPU 负载、内存用量或网络流量等指标触发。These rules can be triggered based on metrics such as CPU load, memory usage, or network traffic.

使用 Azure 平台映像时,规模集最多支持 1,000 个 VM。Scale sets support up to 1,000 VMs when you use an Azure platform image. 对于有重要安装或 VM 自定义要求的工作负荷,可能需要创建自定义 VM 映像For workloads with significant installation or VM customization requirements, you may wish to Create a custom VM image. 使用自定义映像时,在规模集中最多可以创建 300 个 VM。You can create up to 300 VMs in a scale set when using a custom image.

创建用于缩放的应用Create an app to scale

对于生产用途,可能需要创建自定义 VM 映像,其中包含已安装和配置的应用程序。For production use, you may wish to Create a custom VM image that includes your application installed and configured. 在本教程中,我们会在首次启动时自定义 VM,以便快速了解规模集的运作方式。For this tutorial, lets customize the VMs on first boot to quickly see a scale set in action.

上一篇教程已介绍如何使用 cloud-init 在首次启动时自定义 Linux 虚拟机In a previous tutorial, you learned How to customize a Linux virtual machine on first boot 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.

在当前 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:

package_upgrade: true
  - nginx
  - nodejs
  - npm
  - 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!')
  - service nginx restart
  - cd "/home/azureuser/myapp"
  - npm init
  - npm install express -y
  - nodejs index.js

创建规模集Create a scale set

使用 az group create 创建资源组,才能创建规模集。Before you can create a scale set, create a resource group with az group create. 以下示例在“eastus”位置创建名为“myResourceGroupScaleSet”的资源组:The following example creates a resource group named myResourceGroupScaleSet in the eastus location:

az group create --name myResourceGroupScaleSet --location eastus

现在,使用 az vmss create 创建虚拟机规模集。Now create a virtual machine scale set with az vmss create. 以下示例创建名为“myScaleSet”的规模集,使用 cloud-int 文件自定义 VM,并生成 SSH 密钥(如果不存在):The following example creates a scale set named myScaleSet, uses the cloud-init file to customize the VM, and generates SSH keys if they do not exist:

az vmss create \
  --resource-group myResourceGroupScaleSet \
  --name myScaleSet \
  --image UbuntuLTS \
  --upgrade-policy-mode automatic \
  --custom-data cloud-init.txt \
  --admin-username azureuser \

创建和配置所有的规模集资源和 VM 需要几分钟时间。It takes a few minutes to create and configure all the scale set resources and VMs. 在 Azure CLI 向你返回提示之后,仍然存在继续运行的后台任务。There are background tasks that continue to run after the Azure CLI returns you to the prompt. 可能还需等待几分钟才能访问应用。It may be another couple of minutes before you can access the app.

允许 Web 流量Allow web traffic

已自动创建一个负载均衡器,作为虚拟机规模集的一部分。A load balancer was created automatically as part of the virtual machine scale set. 负载均衡器使用负载均衡器规则将流量分配到一组定义的 VM。The load balancer distributes traffic across a set of defined VMs using load balancer rules. 可以在下一篇教程如何对 Azure 中的虚拟机进行负载均衡中详细了解负载均衡器的概念和配置。You can learn more about load balancer concepts and configuration in the next tutorial, How to load balance virtual machines in Azure.

若要允许通信流到达 Web 应用,请使用 az network lb rule create 创建一个规则。To allow traffic to reach the web app, create a rule with az network lb rule create. 以下示例创建名为“myLoadBalancerRuleWeb”的规则:The following example creates a rule named myLoadBalancerRuleWeb:

az network lb rule create \
  --resource-group myResourceGroupScaleSet \
  --name myLoadBalancerRuleWeb \
  --lb-name myScaleSetLB \
  --backend-pool-name myScaleSetLBBEPool \
  --backend-port 80 \
  --frontend-ip-name loadBalancerFrontEnd \
  --frontend-port 80 \
  --protocol tcp

测试应用Test your app

若要在 Web 上查看 Node.js 应用,请使用 az network public-ip show 获取负载均衡器的公共 IP 地址。To see your Node.js app on the web, obtain the public IP address of your load balancer with az network public-ip show. 以下示例获取创建为规模集一部分的“myScaleSetLBPublicIP”的 IP 地址:The following example obtains the IP address for myScaleSetLBPublicIP created as part of the scale set:

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

将公共 IP 地址输入到 Web 浏览器中。Enter the public IP address in to a web browser. 将显示应用,包括负载均衡器将流量分发到的 VM 的主机名:The app is displayed, including the hostname of the VM that the load balancer distributed traffic to:

运行 Node.js 应用

若要查看规模集的运作方式,可以强制刷新 Web 浏览器,以查看负载均衡器如何在运行应用的所有 VM 之间分配流量。To see the scale set in action, you can force-refresh your web browser to see the load balancer distribute traffic across all the VMs running your app.

管理任务Management tasks

在规模集的整个生命周期内,可能需要运行一个或多个管理任务。Throughout the lifecycle of the scale set, you may need to run one or more management tasks. 此外,可能还需要创建自动执行各种生命周期任务的脚本。Additionally, you may want to create scripts that automate various lifecycle-tasks. Azure CLI 2.0 提供一种用于执行这些任务的快速方法。The Azure CLI 2.0 provides a quick way to do those tasks. 以下是一些常见任务。Here are a few common tasks.

查看规模集中的 VMView VMs in a scale set

若要查看规模集中运行的 VM 列表,请使用 az vmss list-instances,如下所示:To view a list of VMs running in your scale set, use az vmss list-instances as follows:

az vmss list-instances \
  --resource-group myResourceGroupScaleSet \
  --name myScaleSet \
  --output table

输出类似于以下示例:The output is similar to the following example:

  InstanceId  LatestModelApplied    Location    Name          ProvisioningState    ResourceGroup            VmId
------------  --------------------  ----------  ------------  -------------------  -----------------------  ------------------------------------
           1  True                  eastus      myScaleSet_1  Succeeded            MYRESOURCEGROUPSCALESET  c72ddc34-6c41-4a53-b89e-dd24f27b30ab
           3  True                  eastus      myScaleSet_3  Succeeded            MYRESOURCEGROUPSCALESET  44266022-65c3-49c5-92dd-88ffa64f95da

手动增加或减少 VM 实例Manually increase or decrease VM instances

若要查看规模集中当前包含的实例数,请使用 az vmss show 并查询 sku.capacity:To see the number of instances you currently have in a scale set, use az vmss show and query on sku.capacity:

az vmss show \
    --resource-group myResourceGroupScaleSet \
    --name myScaleSet \
    --query [sku.capacity] \
    --output table

然后,可以使用 az vmss scale 手动增加或减少规模集中虚拟机的数目。You can then manually increase or decrease the number of virtual machines in the scale set with az vmss scale. 以下示例将规模集中 VM 的数目设置为 3The following example sets the number of VMs in your scale set to 3:

az vmss scale \
    --resource-group myResourceGroupScaleSet \
    --name myScaleSet \
    --new-capacity 3

获取连接信息Get connection info

若要获取有关规模集中 VM 的连接信息,请使用 az vmss list-instance-connection-infoTo obtain connection information about the VMs in your scale sets, use az vmss list-instance-connection-info. 此命令为每个允许采用 SSH 进行连接的 VM 输出公共 IP 地址和端口:This command outputs the public IP address and port for each VM that allows you to connect with SSH:

az vmss list-instance-connection-info \
    --resource-group myResourceGroupScaleSet \
    --name myScaleSet

将数据磁盘与规模集配合使用Use data disks with scale sets

可以创建数据磁盘并与规模集配合使用。You can create and use data disks with scale sets. 前面的教程介绍了如何管理 Azure 磁盘,其中概述了在数据磁盘而非 OS 磁盘上生成应用的最佳做法和性能改进。In a previous tutorial, you learned how to Manage Azure disks that outlines the best practices and performance improvements for building apps on data disks rather than the OS disk.

创建具有数据磁盘的规模集Create scale set with data disks

要创建规模集并附加数据磁盘,请将 --data-disk-sizes-gb 参数添加到 az vmss create 命令中。To create a scale set and attach data disks, add the --data-disk-sizes-gb parameter to the az vmss create command. 以下示例创建具有附加到每个实例的 50 GB 数据磁盘的规模集:The following example creates a scale set with 50Gb data disks attached to each instance:

az vmss create \
    --resource-group myResourceGroupScaleSet \
    --name myScaleSetDisks \
    --image UbuntuLTS \
    --upgrade-policy-mode automatic \
    --custom-data cloud-init.txt \
    --admin-username azureuser \
    --generate-ssh-keys \
    --data-disk-sizes-gb 50

删除规模集中的实例时,也会删除所有附加的数据磁盘。When instances are removed from a scale set, any attached data disks are also removed.

添加数据磁盘Add data disks

若要向规模集中的实例添加数据磁盘,请使用 az vmss disk attachTo add a data disk to instances in your scale set, use az vmss disk attach. 以下示例向每个实例添加一个 50 GB 的磁盘:The following example adds a 50Gb disk to each instance:

az vmss disk attach \
    --resource-group myResourceGroupScaleSet \
    --name myScaleSet \
    --size-gb 50 \
    --lun 2

分离数据磁盘Detach data disks

若要删除附加到规模集中实例的数据磁盘,请使用 az vmss disk detachTo remove a data disk to instances in your scale set, use az vmss disk detach. 以下示例在 LUN 2 删除每个实例中的数据磁盘:The following example removes the data disk at LUN 2 from each instance:

az vmss disk detach \
    --resource-group myResourceGroupScaleSet \
    --name myScaleSet \
    --lun 2

后续步骤Next steps

在本教程中,已创建虚拟机规模集。In this tutorial, you created a virtual machine scale set. 你已了解如何:You learned how to:

  • 使用 cloud-init 创建用于缩放的应用Use cloud-init to create an app to scale
  • 创建虚拟机规模集Create a virtual machine scale set
  • 增加或减少规模集中的实例数Increase or decrease the number of instances in a scale set
  • 创建自动缩放规则Create autoscale rules
  • 查看规模集实例的连接信息View connection info for scale set instances
  • 在规模集中使用数据磁盘Use data disks in a scale set

请继续学习下一篇教程,详细了解虚拟机的负载均衡概念。Advance to the next tutorial to learn more about load balancing concepts for virtual machines.