教學課程:使用 Azure CLI 在 Linux 上建立虛擬機器擴展集及部署高可用性應用程式Tutorial: Create a virtual machine scale set and deploy a highly available app on Linux with the Azure CLI

虛擬機器擴展集可讓您部署和管理一組相同、自動調整的虛擬機器。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 是裝載於 Azure 中的互動式殼層環境,並且會透過瀏覽器來使用。Azure Cloud Shell is an interactive shell environment hosted in Azure and used through your browse. Azure Cloud Shell 可讓您使用 bashPowerShell 殼層來執行各種可與 Azure 服務搭配運作的工具。Azure Cloud Shell allows you to use either bash or PowerShell shells to run a variety of tools to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文的內容,而不必在本機環境上安裝任何工具。Azure Cloud Shell comes pre-installed with the commands to allow you to run the content of this article without having to install anything on your local environment.

若要在 Azure Cloud Shell 上執行本文所包含的任何程式碼,請開啟 Cloud Shell 工作階段、使用某個程式碼區塊上的 [複製] 按鈕來複製程式碼,然後使用 Ctrl+Shift+V (在 Windows 和 Linux 上) 或 Cmd+Shift+V (在 macOS 上) 將程式碼貼到 Cloud Shell 工作階段中。To run any code contained in this article on Azure Cloud Shell, open a Cloud Shell session, use the Copy button on a code block to copy the code, and paste it into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS. 貼上的文字不會自動執行,因此請按 Enter 來執行程式碼。Pasted text is not automatically executed, so press Enter to run code.

您可以使用下列方式來啟動 Azure Cloud Shell:You can launch Azure Cloud Shell with:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 這__不會__自動將文字複製到 Cloud Shell。This doesn't automatically copy text to Cloud Shell. Azure Cloud Shell 的試試看範例
在瀏覽器中開啟 Azure Cloud ShellOpen Azure Cloud Shell in your browser. <a href="https://shell.azure.com" title="啟動 Azure Cloud Shell
選取 Azure 入口網站右上角功能表上的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the menu in the upper-right corner of the Azure portal. Azure 入口網站中的 [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 CLIIf you need to install or upgrade, see Install Azure CLI.

擴展集概觀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.

您目前的殼層中,建立名為 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 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 \
  --generate-ssh-keys

建立及設定所有擴展集資源和 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

在 Web 瀏覽器中輸入公用 IP 位址。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 提供快速的方式來執行這些工作。The Azure CLI 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. 此命令會輸出每部 VM 的公用 IP 位址和連接埠,可讓您與 SSH 連線︰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. 下列範例會建立有 50GB 資料磁碟且連結到每個執行個體的擴展集︰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. 下列範例會將 50GB 的磁碟新增到每個執行個體: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.