快速入门:使用 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. 本快速入门将使用 Azure 资源管理器模板(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 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

如果选择在本地安装并使用 CLI,本快速入门要求运行 Azure CLI 2.0.61 版或更高版本。If you choose to install and use the CLI locally, this quickstart requires that you are running the Azure CLI version 2.0.61 or later. 运行 az --version 即可查找版本。Run az --version to find the version. 如果需要进行安装或升级,请参阅安装 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

备注

在 Azure China 中使用 Azure CLI 2.0 之前,请首先运行 az cloud set -n AzureChinaCloud 更改云环境。Before you can use Azure CLI 2.0 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 Global Azure, run az cloud set -n AzureCloud again.

先决条件Prerequisites

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

若要使用资源管理器模板创建 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.

以下命令使用 RSA 加密和位长度 2048 创建 SSH 密钥对: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"
}

记下 appIdpasswordMake 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,
            "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."
            },
            "minValue": 0,
            "maxValue": 1023
        },
        "agentCount": {
            "type": "int",
            "defaultValue": 3,
            "metadata": {
                "description": "The number of nodes for the cluster."
            },
            "minValue": 1,
            "maxValue": 50
        },
        "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'"
            }
        },
        "servicePrincipalClientId": {
            "metadata": {
                "description": "Client ID (used by cloudprovider)"
            },
            "type": "securestring"
        },
        "servicePrincipalClientSecret": {
            "metadata": {
                "description": "The Service Principal Client Secret."
            },
            "type": "securestring"
        },
        "osType": {
            "type": "string",
            "defaultValue": "Linux",
            "allowedValues": [
                "Linux"
            ],
            "metadata": {
                "description": "The type of operating system."
            }
        }        
    },
    "resources": [
        {
            "apiVersion": "2020-03-01",
            "type": "Microsoft.ContainerService/managedClusters",
            "location": "[parameters('location')]",
            "name": "[parameters('clusterName')]",
            "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')]"
                            }
                        ]
                    }
                },
                "servicePrincipalProfile": {
                    "clientId": "[parameters('servicePrincipalClientId')]",
                    "Secret": "[parameters('servicePrincipalClientSecret')]"
                }
            }
        }
    ],
    "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.

    部署到 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).
    • 服务主体客户端 ID:复制并粘贴 az ad sp create-for-rbac 命令输出的、服务主体的 appIdService 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 命令输出的、服务主体的 passwordService 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 Kubernetes 服务群集的资源管理器模板

  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 本地 Shell,则 kubectl 已安装。If you use Azure local 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. 确保所有节点的状态为“就绪”: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 desired state for the cluster, such as what container images to run. 在本快速入门中,清单用于创建运行 Azure Vote 应用程序所需的所有对象。In this quickstart, a manifest is used to create all objects needed to run the Azure Vote application. 此清单包括两个 Kubernetes 部署 - 一个用于 Azure Vote 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 实例,一个外部服务用于从 Internet 访问 Azure Vote 应用程序。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 本地 Shell,则可以使用 vinano 来创建此文件,就像在虚拟或物理系统中操作一样:If you use the Azure local 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: redis
        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 服务将向 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.

若要监视进度,请将 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 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

如果不再需要群集,可以使用 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. GitHub 上提供了相关的应用程序代码、Dockerfile 和 Kubernetes 清单文件。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.