快速入门:使用 ARM 模板部署 Azure Kubernetes 服务 (AKS) 群集Quickstart: Deploy an Azure Kubernetes Service (AKS) cluster using an ARM template

Azure Kubernetes 服务 (AKS) 是可用于快速部署和管理群集的托管式 Kubernetes 服务。Azure Kubernetes Service (AKS) is a managed Kubernetes service that lets you quickly deploy and manage clusters. 在本快速入门中,请执行以下操作:In this quickstart, you will:

  • 使用 Azure 资源管理器模板部署 AKS 群集。Deploy an AKS cluster using an Azure Resource Manager template.
  • 在该群集中运行一个包含 Web 前端和 Redis 实例的多容器应用程序。Run a multi-container application with a web front-end and a Redis instance in the cluster.

浏览到 Azure Vote 的图像

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, which lets you state what you intend to deploy without having to write the sequence of programming commands to create it.

本快速入门假设读者基本了解 Kubernetes 的概念。This quickstart assumes a basic understanding of Kubernetes concepts. 有关详细信息,请参阅 Azure Kubernetes 服务 (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.

部署到 Azure Deploy to Azure

如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin.

先决条件Prerequisites

  • 如果需要,请安装 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 CLIFor 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.

  • 本文需要 Azure CLI 版本 2.0.61 或更高版本。This article requires version 2.0.61 or later of the Azure CLI.

  • 若要使用资源管理器模板创建 AKS 群集,请提供 SSH 公钥。To create an AKS cluster using a Resource Manager template, you provide an SSH public key. 如果需要此资源,请参阅以下部分;否则请跳到查看模板部分。If you need this resource, see the following section; otherwise skip to the Review the template section.

备注

请先运行 az cloud set -n AzureChinaCloud 更改云环境,然后才能在 Azure 中国中使用 Azure CLI。Before you can use Azure CLI in Azure China , please run az cloud set -n AzureChinaCloud first to change the cloud environment. 若要切换回 Azure 公有云,请再次运行 az cloud set -n AzureCloudIf you want to switch back to Azure Public Cloud, run az cloud set -n AzureCloud again.

创建 SSH 密钥对Create an SSH key pair

若要访问 AKS 节点,请使用通过 ssh-keygen 命令生成的 SSH 密钥对(公钥和私钥)进行连接。To access AKS nodes, you connect using an SSH key pair (public and private), which you generate using the ssh-keygen command. 默认情况下,这些文件在 ~/.ssh 目录中创建。By default, these files are created in the ~/.ssh directory. 运行 ssh-keygen 命令会覆盖给定位置中同名的任何 SSH 密钥对。Running the ssh-keygen command will overwrite any SSH key pair with the same name already existing in the given location.

  1. 运行 ssh-keygen 命令。Run the ssh-keygen command. 以下示例使用 RSA 加密和 2048 位长度创建 SSH 密钥对:The following example 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.

查看模板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 button to sign in to Azure and open a template.

    部署到 Azure Deploy 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.
    • 位置:选择一个位置,例如“中国东部 2”。Location: Select a location, such as China East 2.
    • 群集名称:输入 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 密钥对的 public 部分(默认为 ~/.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).

    用于在门户中创建 Azure Kubernetes 服务群集的资源管理器模板

  3. 勾选“我同意上述条款和条件”。Tick the I agree to the terms and conditions stated above.

  4. 选择“购买”。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, use the Kubernetes command-line client, kubectl.

  1. 在本地使用 az aks install-cli 命令安装 kubectlInstall kubectl locally using the az aks install-cli command:

    az aks install-cli
    
  2. 使用 az aks get-credentials 命令将 kubectl 配置为连接到你的 Kubernetes 群集。Configure kubectl to connect to your Kubernetes cluster using 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
    
  3. 使用 kubectl get 命令验证与群集之间的连接。Verify the connection to your cluster using the kubectl get command. 此命令将返回群集节点的列表。This command returns a list of the cluster nodes.

    kubectl get nodes
    

    输出将显示前面步骤中创建的节点。Output shows the nodes created in the previous steps. 确保所有节点的状态为“就绪”:Make 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 cluster's desired state, such as which container images to run.

在本快速入门中,你将使用清单来创建运行 Azure Vote 应用程序所需的所有对象。In this quickstart, you will use a manifest to create all objects needed to run the Azure Vote application. 此清单包含两个 Kubernetes 部署This manifest includes two Kubernetes deployments:

  • 示例 Azure Vote Python 应用程序。The sample Azure Vote Python applications.
  • 一个 Redis 实例。A Redis instance.

此外,还会创建两个 Kubernetes 服务Two Kubernetes Services are also created:

  • Redis 实例的内部服务。An internal service for the Redis instance.
  • 用于通过 Internet 访问 Azure Vote 应用程序的外部服务。An external service to access the Azure Vote application from the internet.
  1. 创建名为 azure-vote.yaml 的文件。Create a file named azure-vote.yaml.

    • 可以使用 vinano 来创建此文件,就像在虚拟或物理系统中操作一样。This file can be created using vi or nano as if working on a virtual or physical system.
  2. 复制以下 YAML 定义:Copy in the following YAML definition:

    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
    
  3. 使用 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
    

    输出显示已成功创建的部署和服务:Output shows the successfully created deployments and services:

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

测试应用程序Test the application

应用程序运行时,Kubernetes 服务将向 Internet 公开应用程序前端。When the application runs, a Kubernetes service exposes the application front end to the internet. 此过程可能需要几分钟才能完成。This process can take a few minutes to complete.

使用带有 --watch 参数的 kubectl get service 命令来监视进度。Monitor progress using the kubectl get service command with the --watch argument.

kubectl get service azure-vote-front --watch

azure-vote-front 服务的 EXTERNAL-IP 输出最初显示为 pendingThe EXTERNAL-IP output for the azure-vote-front service will initially show 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 监视进程。Once 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 Vote 应用的实际效果,请打开 Web 浏览器并转到服务的外部 IP 地址。To see the Azure Vote app in action, open a web browser to the external IP address of your service.

浏览到 Azure Vote 的图像

清理资源Clean up resources

为了避免产生 Azure 费用,请清理不需要的资源。To avoid Azure charges, clean up your unnecessary resources. 可以使用 az group delete 命令删除资源组、容器服务及所有相关资源。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 部署。Pre-existing container images were used in this quickstart to create a Kubernetes deployment. GitHub 上提供了相关的应用程序代码、Dockerfile 和 Kubernetes 清单文件。The related application code, Dockerfile, and Kubernetes manifest file are available on GitHub.

后续步骤Next steps

在本快速入门中,你部署了一个 Kubernetes 群集,然后在其中部署了多容器应用程序。In this quickstart, you deployed a Kubernetes cluster and then deployed a multi-container application to it. 访问 AKS 群集的 Kubernetes Web 仪表板Access the Kubernetes web dashboard for your AKS cluster.

若要详细了解 AKS 并演练部署示例的完整代码,请继续阅读“Kubernetes 群集”教程。To learn more about AKS, and walk through a complete code to deployment example, continue to the Kubernetes cluster tutorial.