教學課程:使用 Azure CLI 平衡 Azure 中 Linux 虛擬機器的負載以建立高可用性應用程式Tutorial: Load balance Linux virtual machines in Azure to create a highly available application with the Azure CLI

負載平衡會將傳入要求分散到多部虛擬機器,藉此提供高可用性。Load balancing provides a higher level of availability by spreading incoming requests across multiple virtual machines. 在本教學課程中,您會了解 Azure Load Balancer 的不同元件,以分散流量並提供高可用性。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 Load BalancerCreate 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
  • 新增和移除虛擬機器的負載平衡器Add and remove VMs from a load balancer

開啟 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.

Azure Load Balancer 概觀Azure load balancer overview

Azure Load Balancer 是 Layer-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 組態允許透過網際網路存取您的負載平衡器和應用程式。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 Load BalancerCreate 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

若要存取網際網路上您的應用程式,您需要負載平衡器的公用 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 對健康狀態檢查的回應,以動態方式從負載平衡器輪替中新增或移除 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

當建立好所有三個虛擬 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. 若要查看作用中的負載平衡器,在本教學課程結尾處,您可以在網頁瀏覽器中存取這個簡單應用程式。To see the load balancer in action, at the end of the tutorial you access this simple app in a web browser.

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

在 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

接著,您可以在 Web 瀏覽器中輸入公用 IP 位址。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 應用程式

若要查看負載平衡器如何將流量分散於執行您應用程式的這三部 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 的識別碼,如下所示: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:


將 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 Load BalancerCreate 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
  • 新增和移除虛擬機器的負載平衡器Add and remove VMs from a load balancer

請前進到下一個教學課程,以深入了解 Azure 虛擬網路元件。Advance to the next tutorial to learn more about Azure virtual network components.