快速入門:使用 ARM 範本部署 Azure Kubernetes Service (AKS) 叢集Quickstart: Deploy an Azure Kubernetes Service (AKS) cluster using an ARM template

Azure Kubernetes Service (AKS) 是受控 Kubernetes 服務,可讓您快速部署及管理叢集。Azure Kubernetes Service (AKS) is a managed Kubernetes service that lets you quickly deploy and manage clusters. 在本快速入門中,您將使用 Azure Resource Manager 範本 (ARM 範本) 部署 AKS 叢集。In this quickstart, you deploy an AKS cluster using an Azure Resource Manager template (ARM template). 在叢集上執行包含 Web 前端和 Redis 執行個體的多容器應用程式。A multi-container application that includes a web front end and a Redis instance is run in the cluster.

瀏覽至 Azure 投票的影像

ARM 範本是一個 JavaScript 物件標記法 (JSON) 檔案,會定義專案的基礎結構和設定。An ARM template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. 範本會使用宣告式語法。The template uses declarative syntax. 在宣告式語法中,您可以描述預期的部署,而不需要撰寫程式設計命令順序來建立部署。In declarative syntax, you describe your intended deployment without writing the sequence of programming commands to create the deployment.

本快速入門假設您已有 Kubernetes 概念的基本知識。This quickstart assumes a basic understanding of Kubernetes concepts. 如需詳細資訊,請參閱 Azure Kubernetes Services (AKS) 的 Kubernetes 核心概念For more information, see Kubernetes core concepts for Azure Kubernetes Service (AKS).

如果您的環境符合必要條件,而且您很熟悉 ARM 範本,請選取 [部署至 Azure] 按鈕。If your environment meets the prerequisites and you're familiar with using ARM templates, select the Deploy to Azure button. 範本會在 Azure 入口網站中開啟。The template will open in the Azure portal.

部署至 AzureDeploy to Azure

如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶If you don't have an Azure subscription, create a free account before you begin.

必要條件Prerequisites

  • 使用 Bash 環境的 Azure Cloud ShellUse Azure Cloud Shell using the Bash environment.

    在新視窗中啟動 Cloud ShellLaunch Cloud Shell in a new window

  • 如果想要,請安裝 Azure CLI 以執行 CLI 參考命令。If you prefer, install the Azure CLI to run CLI reference commands.

    • 如果您使用的是本機安裝,請使用 az login 命令,透過 Azure CLI 來登入。If you're using a local installation, sign in to the Azure CLI by using the az login command. 請遵循您終端機上顯示的步驟,完成驗證程序。To finish the authentication process, follow the steps displayed in your terminal. 如需其他登入選項,請參閱使用 Azure CLI 登入For additional sign-in options, see Sign in with the Azure CLI.
    • 出現提示時,請在第一次使用時安裝 Azure CLI 擴充功能。When you're prompted, install Azure CLI extensions on first use. 如需擴充功能詳細資訊,請參閱使用 Azure CLI 擴充功能For more information about extensions, see Use extensions with the Azure CLI.
    • 執行 az version 以尋找已安裝的版本和相依程式庫。Run az version to find the version and dependent libraries that are installed. 若要升級至最新版本,請執行 az upgradeTo upgrade to the latest version, run az upgrade.
  • 本文需要 2.0.61 版或更新版本的 Azure CLI。This article requires version 2.0.61 or later of the Azure CLI. 如果您是使用 Azure Cloud Shell,就已安裝最新版本。If using Azure Cloud Shell, the latest version is already installed.

  • 若要使用 Resource Manager 範本建立 AKS 叢集,您必須提供 SSH 公開金鑰與 Azure Active Directory 服務主體。To create an AKS cluster using a Resource Manager template, you provide an SSH public key and Azure Active Directory service principal. 您也可以使用受控識別而不是服務主體的權限。Alternatively, you can use a managed identity instead of a service principal for permissions. 如果您需要其中一個資源,請參閱下一節;否則請跳至檢閱範本一節。If you need either of these resources, see the following section; otherwise skip to the Review the template section.

建立 SSH 金鑰組Create an SSH key pair

若要存取 AKS 節點,您可以使用 SSH 金鑰組進行連線。To access AKS nodes, you connect using an SSH key pair. 使用 ssh-keygen 命令來產生 SSH 公開和私密金鑰檔案。Use the ssh-keygen command to generate SSH public and private key files. 根據預設,這些檔案會建立在 ~/.ssh 目錄中。By default, these files are created in the ~/.ssh directory. 如果指定位置中存在相同名稱的 SSH 金鑰組,則系統會覆寫那些檔案。If an SSH key pair with the same name exists in the given location, those files are overwritten.

移至 https://shell.azure.com,並在您的瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com to open Cloud Shell in your browser.

下列命令會使用 RSA 加密建立 SSH 金鑰組,位元長度為 2048:The following command creates an SSH key pair using RSA encryption and a bit length of 2048:

ssh-keygen -t rsa -b 2048

如需建立 SSH 金鑰的詳細資訊,請參閱在 Azure 中建立及管理驗證的 SSH 金鑰For more information about creating SSH keys, see Create and manage SSH keys for authentication in Azure.

建立服務主體Create a service principal

為了允許 AKS 叢集與其他 Azure 資源互動,則會使用 Azure Active Directory 服務主體。To allow an AKS cluster to interact with other Azure resources, an Azure Active Directory service principal is used. 使用 az ad sp create-for-rbac 命令建立服務主體。Create a service principal using the az ad sp create-for-rbac command. --skip-assignment 參數會限制指派任何其他權限。The --skip-assignment parameter limits any additional permissions from being assigned. 根據預設,此服務主體的有效期限為一年。By default, this service principal is valid for one year. 請注意,您也可以使用受控識別而不是服務主體。Note that you can use a managed identity instead of a service principal. 如需詳細資訊,請參閱使用受控識別For more information, see Use managed identities.

az ad sp create-for-rbac --skip-assignment

輸出類似於下列範例:The output is similar to the following example:

{
  "appId": "8b1ede42-d407-46c2-a1bc-6b213b04295f",
  "displayName": "azure-cli-2019-04-19-21-42-11",
  "name": "http://azure-cli-2019-04-19-21-42-11",
  "password": "27e5ac58-81b0-46c1-bd87-85b4ef622682",
  "tenant": "73f978cf-87f2-41bf-92ab-2e7ce012db57"
}

記下 appId 和密碼。Make a note of the appId and password. 下列步驟中會使用這些值。These values are used in the following steps.

檢閱範本Review the template

本快速入門中使用的範本是來自 Azure 快速入門範本The template used in this quickstart is from Azure Quickstart templates.

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.1",
  "parameters": {
    "clusterName": {
      "type": "string",
      "defaultValue": "aks101cluster",
      "metadata": {
        "description": "The name of the Managed Cluster resource."
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "The location of the Managed Cluster resource."
      }
    },
    "dnsPrefix": {
      "type": "string",
      "metadata": {
        "description": "Optional DNS prefix to use with hosted Kubernetes API server FQDN."
      }
    },
    "osDiskSizeGB": {
      "type": "int",
      "defaultValue": 0,
      "minValue": 0,
      "maxValue": 1023,
      "metadata": {
        "description": "Disk size (in GB) to provision for each of the agent pool nodes. This value ranges from 0 to 1023. Specifying 0 will apply the default disk size for that agentVMSize."
      }
    },
    "agentCount": {
      "type": "int",
      "defaultValue": 3,
      "minValue": 1,
      "maxValue": 50,
      "metadata": {
        "description": "The number of nodes for the cluster."
      }
    },
    "agentVMSize": {
      "type": "string",
      "defaultValue": "Standard_DS2_v2",
      "metadata": {
        "description": "The size of the Virtual Machine."
      }
    },
    "linuxAdminUsername": {
      "type": "string",
      "metadata": {
        "description": "User name for the Linux Virtual Machines."
      }
    },
    "sshRSAPublicKey": {
      "type": "string",
      "metadata": {
        "description": "Configure all linux machines with the SSH RSA public key string. Your key should include three parts, for example 'ssh-rsa AAAAB...snip...UcyupgH azureuser@linuxvm'"
      }
    },
    "osType": {
      "type": "string",
      "defaultValue": "Linux",
      "allowedValues": [
        "Linux"
      ],
      "metadata": {
        "description": "The type of operating system."
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.ContainerService/managedClusters",
      "apiVersion": "2020-03-01",
      "name": "[parameters('clusterName')]",
      "location": "[parameters('location')]",
      "properties": {
        "dnsPrefix": "[parameters('dnsPrefix')]",
        "agentPoolProfiles": [
          {
            "name": "agentpool",
            "osDiskSizeGB": "[parameters('osDiskSizeGB')]",
            "count": "[parameters('agentCount')]",
            "vmSize": "[parameters('agentVMSize')]",
            "osType": "[parameters('osType')]",
            "storageProfile": "ManagedDisks"
          }
        ],
        "linuxProfile": {
          "adminUsername": "[parameters('linuxAdminUsername')]",
          "ssh": {
            "publicKeys": [
              {
                "keyData": "[parameters('sshRSAPublicKey')]"
              }
            ]
          }
        }
      },
      "identity": {
          "type": "SystemAssigned"
      }
    }
  ],
  "outputs": {
    "controlPlaneFQDN": {
      "type": "string",
      "value": "[reference(parameters('clusterName')).fqdn]"
    }
  }
}

如需更多 AKS 範例,請參閱 AKS 快速入門範本站台。For more AKS samples, see the AKS quickstart templates site.

部署範本Deploy the template

  1. 選取以下影像來登入 Azure 並開啟範本。Select the following image to sign in to Azure and open a template.

    部署至 AzureDeploy to Azure

  2. 選取或輸入下列值。Select or enter the following values.

    在本快速入門中,請保留 [OS 磁碟大小 GB]、[代理程式計數]、[代理程式 VM 大小]、[OS 類型] 和 [Kubernetes 版本] 的預設值。For this quickstart, leave the default values for the OS Disk Size GB, Agent Count, Agent VM Size, OS Type, and Kubernetes Version. 請針對下列範本參數提供您自己的值︰Provide your own values for the following template parameters:

    • 訂用帳戶:選取 Azure 訂用帳戶。Subscription: Select an Azure subscription.
    • 資源群組:選取 [建立新的]。Resource group: Select Create new. 輸入資源群組的唯一名稱 (例如 myResourceGroup),然後選擇 [確定]。Enter a unique name for the resource group, such as myResourceGroup, then choose OK.
    • 位置:選取一個位置,例如 [美國東部]。Location: Select a location, such as East US.
    • 叢集名稱:輸入 AKS 叢集的唯一名稱,例如 myAKSClusterCluster name: Enter a unique name for the AKS cluster, such as myAKSCluster.
    • DNS 前置詞:為您的叢集輸入唯一的 DNS 前置詞,例如 myaksclusterDNS prefix: Enter a unique DNS prefix for your cluster, such as myakscluster.
    • Linux 管理員使用者名稱:輸入使用 SSH 連線的使用者名稱,例如 azureuserLinux Admin Username: Enter a username to connect using SSH, such as azureuser.
    • SSH RSA 公開金鑰:複製並貼上 SSH 金鑰組的 公開 部分 (預設為 ~/.ssh/id_rsa.pub 的內容)。SSH RSA Public Key: Copy and paste the public part of your SSH key pair (by default, the contents of ~/.ssh/id_rsa.pub).
    • 服務主體用戶端識別碼:從 az ad sp create-for-rbac 命令中複製並貼上您服務主體的 應用程式識別碼Service Principal Client Id: Copy and paste the appId of your service principal from the az ad sp create-for-rbac command.
    • 服務主體用戶端密碼:從 az ad sp create-for-rbac 命令中複製並貼上您服務主體的 密碼Service Principal Client Secret: Copy and paste the password of your service principal from the az ad sp create-for-rbac command.
    • 我同意上方所述的條款及條件:核取此方塊以表示同意。I agree to the terms and conditions state above: Check this box to agree.

    在入口網站中建立 Azure Container Service 叢集的 Resource Manager 範本

  3. 選取 [購買]。Select Purchase.

建立 AKS 叢集需要幾分鐘的時間。It takes a few minutes to create the AKS cluster. 請等到叢集成功部署後,再移至下一個步驟。Wait for the cluster to be successfully deployed before you move on to the next step.

驗證部署Validate the deployment

連線至叢集Connect to the cluster

若要管理 Kubernetes 叢集,請使用 Kubernetes 命令列用戶端:kubectlTo manage a Kubernetes cluster, you use kubectl, the Kubernetes command-line client. 如果您使用 Azure Cloud Shell,則 kubectl 已安裝。If you use Azure Cloud Shell, kubectl is already installed. 若要在本機安裝 kubectl,請使用 az aks install-cli 命令:To install kubectl locally, use the az aks install-cli command:

az aks install-cli

若要設定 kubectl 以連線到 Kubernetes 叢集,請使用 az aks get-credentials 命令。To configure kubectl to connect to your Kubernetes cluster, use the az aks get-credentials command. 此命令會下載憑證並設定 Kubernetes CLI 以供使用。This command downloads credentials and configures the Kubernetes CLI to use them.

az aks get-credentials --resource-group myResourceGroup --name myAKSCluster

若要驗證針對您叢集的連線,請使用 kubectl get 命令來傳回叢集節點的清單。To verify the connection to your cluster, use the kubectl get command to return a list of the cluster nodes.

kubectl get nodes

下列輸出範例會顯示上一個步驟中建立的節點。The following example output shows the nodes created in the previous steps. 請確定所有節點的狀態皆為 ReadyMake sure that the status for all the nodes is Ready:

NAME                       STATUS   ROLES   AGE     VERSION
aks-agentpool-41324942-0   Ready    agent   6m44s   v1.12.6
aks-agentpool-41324942-1   Ready    agent   6m46s   v1.12.6
aks-agentpool-41324942-2   Ready    agent   6m45s   v1.12.6

執行應用程式Run the application

Kubernetes 資訊清單檔會定義所需的叢集狀態,例如要執行哪些容器映像。A Kubernetes manifest file defines a desired state for the cluster, such as what container images to run. 在本教學課程中,資訊清單可用來建立執行 Azure 投票應用程式所需的所有物件。In this quickstart, a manifest is used to create all objects needed to run the Azure Vote application. 此資訊清單包含兩個 Kubernetes 部署:一個適用於範例 Azure 投票 Python 應用程式,而另一個適用於 Redis 執行個體。This manifest includes two Kubernetes deployments - one for the sample Azure Vote Python applications, and the other for a Redis instance. 還會建立兩個 Kubernetes 服務:內部服務用於 Redis 執行個體,而外部服務用於從網際網路存取 Azure 投票應用程式。Two Kubernetes Services are also created - an internal service for the Redis instance, and an external service to access the Azure Vote application from the internet.

建立名為 azure-vote.yaml 的檔案,然後將下列 YAML 定義複製進來。Create a file named azure-vote.yaml and copy in the following YAML definition. 如果您使用 Azure Cloud Shell,可以使用 vinano 建立這個檔案,猶如使用虛擬或實體系統:If you use the Azure Cloud Shell, this file can be created using vi or nano as if working on a virtual or physical system:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: azure-vote-back
spec:
  replicas: 1
  selector:
    matchLabels:
      app: azure-vote-back
  template:
    metadata:
      labels:
        app: azure-vote-back
    spec:
      nodeSelector:
        "beta.kubernetes.io/os": linux
      containers:
      - name: azure-vote-back
        image: mcr.microsoft.com/oss/bitnami/redis:6.0.8
        env:
        - name: ALLOW_EMPTY_PASSWORD
          value: "yes"
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 250m
            memory: 256Mi
        ports:
        - containerPort: 6379
          name: redis
---
apiVersion: v1
kind: Service
metadata:
  name: azure-vote-back
spec:
  ports:
  - port: 6379
  selector:
    app: azure-vote-back
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: azure-vote-front
spec:
  replicas: 1
  selector:
    matchLabels:
      app: azure-vote-front
  template:
    metadata:
      labels:
        app: azure-vote-front
    spec:
      nodeSelector:
        "beta.kubernetes.io/os": linux
      containers:
      - name: azure-vote-front
        image: mcr.microsoft.com/azuredocs/azure-vote-front:v1
        resources:
          requests:
            cpu: 100m
            memory: 128Mi
          limits:
            cpu: 250m
            memory: 256Mi
        ports:
        - containerPort: 80
        env:
        - name: REDIS
          value: "azure-vote-back"
---
apiVersion: v1
kind: Service
metadata:
  name: azure-vote-front
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: azure-vote-front

使用 kubectl apply 命令來部署應用程式並指定 YAML 資訊清單的名稱:Deploy the application using the kubectl apply command and specify the name of your YAML manifest:

kubectl apply -f azure-vote.yaml

下列範例輸出會顯示已成功建立的部署和服務:The following example output shows the Deployments and Services created successfully:

deployment "azure-vote-back" created
service "azure-vote-back" created
deployment "azure-vote-front" created
service "azure-vote-front" created

測試應用程式Test the application

執行應用程式時,Kubernetes 服務會向網際網路公開前端應用程式。When the application runs, a Kubernetes service exposes the application front end to the internet. 此程序需要數分鐘的時間完成。This process can take a few minutes to complete.

若要監視進度,請使用 kubectl get service 命令搭配 --watch 引數。To monitor progress, use the kubectl get service command with the --watch argument.

kubectl get service azure-vote-front --watch

一開始,azure-vote-front 服務的 EXTERNAL-IP 會顯示為 pendingInitially the EXTERNAL-IP for the azure-vote-front service is shown as pending.

NAME               TYPE           CLUSTER-IP   EXTERNAL-IP   PORT(S)        AGE
azure-vote-front   LoadBalancer   10.0.37.27   <pending>     80:30572/TCP   6s

EXTERNAL-IP 位址從 pending 變成實際的公用 IP 位址時,請使用 CTRL-C 停止 kubectl 監看式流程。When the EXTERNAL-IP address changes from pending to an actual public IP address, use CTRL-C to stop the kubectl watch process. 下列範例輸出會顯示已指派給服務的有效公用 IP 位址:The following example output shows a valid public IP address assigned to the service:

azure-vote-front   LoadBalancer   10.0.37.27   52.179.23.131   80:30572/TCP   2m

若要查看 Azure 投票應用程式的實際運作情況,請開啟網頁瀏覽器並瀏覽至服務的外部 IP 位址。To see the Azure Vote app in action, open a web browser to the external IP address of your service.

瀏覽至 Azure 投票的影像

清除資源Clean up resources

若不再需要叢集,可使用 az group delete 命令來移除資源群組、容器服務和所有相關資源。When the cluster is no longer needed, use the az group delete command to remove the resource group, container service, and all related resources.

az group delete --name myResourceGroup --yes --no-wait

注意

當您刪除叢集時,不會移除 AKS 叢集所使用的 Azure Active Directory 服務主體。When you delete the cluster, the Azure Active Directory service principal used by the AKS cluster is not removed. 如需有關如何移除服務主體的步驟,請參閱 AKS 服務主體的考量和刪除For steps on how to remove the service principal, see AKS service principal considerations and deletion. 如果您使用受控識別,則身分識別會由平台負責管理,您不需要刪除。If you used a managed identity, the identity is managed by the platform and does not require removal.

取得程式碼Get the code

在本快速入門中,預先建立的容器映像已用來建立 Kubernetes 部署。In this quickstart, pre-created container images were used to create a Kubernetes deployment. 相關的應用程式程式碼、Dockerfile 和 Kubernetes 資訊清單檔案,都可以在 GitHub 上取得。The related application code, Dockerfile, and Kubernetes manifest file are available on GitHub.

https://github.com/Azure-Samples/azure-voting-app-redis

後續步驟Next steps

在本快速入門中,您已部署 Kubernetes 叢集,並將多容器應用程式部署到此叢集。In this quickstart, you deployed a Kubernetes cluster and deployed a multi-container application to it. 存取 Kubernetes Web 儀表板,以使用您已建立的叢集。Access the Kubernetes web dashboard for the cluster you created.

若要深入了解 AKS,並逐步完成部署範例的完整程式碼,請繼續 Kubernetes 叢集教學課程。To learn more about AKS, and walk through a complete code to deployment example, continue to the Kubernetes cluster tutorial.