你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

快速入门:使用 ARM 模板部署 Azure Kubernetes 服务 (AKS) 群集

Azure Kubernetes 服务 (AKS) 是可用于快速部署和管理群集的托管式 Kubernetes 服务。 在本快速入门中,请执行以下操作:

  • 使用 Azure 资源管理器模板部署 AKS 群集。
  • 使用一组微服务和模拟零售场景的 Web 前端运行示例多容器应用程序。

Azure 资源管理器模板是定义项目基础结构和配置的 JavaScript 对象表示法 (JSON) 文件。 模板使用声明性语法。 你可以在不编写用于创建部署的编程命令序列的情况下,描述预期部署。

注意

为了开始快速预配 AKS 群集,本文介绍了仅针对评估目的部署具有默认设置的群集的步骤。 在部署生产就绪群集之前,建议熟悉我们的基线参考体系结构,考虑它如何与你的业务需求保持一致。

开始之前

本文假定你对 Kubernetes 概念有基本的了解。 有关详细信息,请参阅 Azure Kubernetes 服务 (AKS) 的 Kubernetes 核心概念

  • 如果没有 Azure 订阅,请在开始之前创建一个 Azure 免费帐户

  • 确保用于创建群集的标识具有适当的最低权限。 有关 AKS 访问和标识的详细信息,请参阅 Azure Kubernetes Service (AKS) 的访问和标识选项

  • 要部署 ARM 模板,需要将要部署和访问的资源的访问权限写入到 Microsoft.Resources/deployments 资源类型的所有操作。 例如,若要部署虚拟机,需要 Microsoft.Compute/virtualMachines/writeMicrosoft.Resources/deployments/* 权限。 有关角色和权限的列表,请参阅 Azure 内置角色

从模板部署群集后,可以使用 Azure CLI 或 Azure PowerShell 连接到群集并部署示例应用程序。

本文需要 Azure CLI 2.0.64 或更高版本。 如果你使用的是 Azure Cloud Shell,则表示已安装最新版本。

创建 SSH 密钥对

若要使用 ARM 模板创建 AKS 群集,请提供 SSH 公钥。 如果需要此资源,请按照本部分中的步骤操作。 否则,请跳到查看模板部分。

若要访问 AKS 节点,请使用 SSH 密钥对(公共和专用)进行连接。 若要创建 SSH 密钥对:

  1. 在浏览器中访问 https://shell.azure.com 以打开 Cloud Shell。

  2. 使用 az sshkey create 命令或 ssh-keygen 命令创建 SSH 密钥对。

    # Create an SSH key pair using Azure CLI
    az sshkey create --name "mySSHKey" --resource-group "myResourceGroup"
    
    # or
    
    # Create an SSH key pair using ssh-keygen
    ssh-keygen -t rsa -b 4096
    
  3. 若要部署模板,必须提供 SSH 对中的公钥。 若要检索公钥,请调用 az sshkey show

    az sshkey show --name "mySSHKey" --resource-group "myResourceGroup" --query "publicKey"
    

默认情况下,SSH 密钥文件是在 ~/.ssh 目录中创建的。 运行 az sshkey createssh-keygen 命令会覆盖任何同名的现有 SSH 密钥对。

有关创建 SSH 密钥的详细信息,请参阅在 Azure 中创建和管理用于身份验证的 SSH 密钥

查看模板

本快速入门中使用的模板来自 Azure 快速启动模板

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.9.1.41621",
      "templateHash": "2637152180661081755"
    }
  },
  "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,
      "maxValue": 1023,
      "minValue": 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."
      }
    },
    "agentCount": {
      "type": "int",
      "defaultValue": 3,
      "maxValue": 50,
      "minValue": 1,
      "metadata": {
        "description": "The number of nodes for the cluster."
      }
    },
    "agentVMSize": {
      "type": "string",
      "defaultValue": "standard_d2s_v3",
      "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'"
      }
    }
  },
  "resources": [
    {
      "type": "Microsoft.ContainerService/managedClusters",
      "apiVersion": "2022-05-02-preview",
      "name": "[parameters('clusterName')]",
      "location": "[parameters('location')]",
      "identity": {
        "type": "SystemAssigned"
      },
      "properties": {
        "dnsPrefix": "[parameters('dnsPrefix')]",
        "agentPoolProfiles": [
          {
            "name": "agentpool",
            "osDiskSizeGB": "[parameters('osDiskSizeGB')]",
            "count": "[parameters('agentCount')]",
            "vmSize": "[parameters('agentVMSize')]",
            "osType": "Linux",
            "mode": "System"
          }
        ],
        "linuxProfile": {
          "adminUsername": "[parameters('linuxAdminUsername')]",
          "ssh": {
            "publicKeys": [
              {
                "keyData": "[parameters('sshRSAPublicKey')]"
              }
            ]
          }
        }
      }
    }
  ],
  "outputs": {
    "controlPlaneFQDN": {
      "type": "string",
      "value": "[reference(resourceId('Microsoft.ContainerService/managedClusters', parameters('clusterName'))).fqdn]"
    }
  }
}

ARM 模板中定义的资源类型是 Microsoft.ContainerService/managedClusters

有关更多 AKS 示例,请参阅 AKS 快速入门模板站点。

部署模板

  1. 选择“部署到 Azure”,登录并打开模板。

    Button to deploy the Resource Manager template to Azure.

  2. 在“基本信息”页上,保留“OS 磁盘大小 GB”、“代理计数”、“代理 VM 大小”以及“OS 类型”的默认值,并配置以下模板参数:

    • 订阅:选择 Azure 订阅。
    • 资源组:选择“新建”。 输入资源组的唯一名称(例如 myResourceGroup),然后选择“确定”。
    • 位置:选择一个位置,例如“美国东部”。
    • 群集名称:输入 AKS 群集的唯一名称,例如 myAKSCluster
    • DNS 前缀:输入群集的唯一 DNS 前缀,例如 myakscluster
    • Linux 管理员用户名:输入一个用户名用于通过 SSH 进行连接,例如 azureuser
    • SSH 公钥源”:选择“使用现有公钥”。
    • 密钥对名称:复制并粘贴 SSH 密钥对的 public 部分(默认为 ~/.ssh/id_rsa.pub 的内容)。
  3. 选择“查看 + 创建”>“创建”。

创建 AKS 群集需要几分钟时间。 等待群集成功部署,然后转到下一步骤。

连接到群集

若要管理 Kubernetes 群集,请使用 Kubernetes 命令行客户端 kubectl

如果使用的是 Azure Cloud Shell,则 kubectl 已安装。 若要在本地安装和运行 kubectl,请调用 az aks install-cli 命令。

  1. 使用 az aks get-credentials 命令将 kubectl 配置为连接到你的 Kubernetes 群集。 此命令将下载凭据,并将 Kubernetes CLI 配置为使用这些凭据。

    az aks get-credentials --resource-group myResourceGroup --name myAKSCluster
    
  2. 使用 kubectl get 命令验证与群集之间的连接。 此命令将返回群集节点的列表。

    kubectl get nodes
    

    以下示例输出显示在上一步骤中创建的三个节点。 确保节点状态为“就绪”。

    NAME                                STATUS   ROLES   AGE   VERSION
    aks-agentpool-27442051-vmss000000   Ready    agent   10m   v1.27.7
    aks-agentpool-27442051-vmss000001   Ready    agent   10m   v1.27.7
    aks-agentpool-27442051-vmss000002   Ready    agent   11m   v1.27.7
    

部署应用程序

若要部署应用程序,请使用清单文件创建运行 AKS 应用商店应用程序所需的所有对象。 Kubernetes 清单文件定义群集的所需状态,例如,要运行哪些容器映像。 该清单包含以下 Kubernetes 部署和服务:

Screenshot of Azure Store sample architecture.

  • 门店:Web 应用程序,供客户查看产品和下单。
  • 产品服务:显示产品信息。
  • 订单服务:下单。
  • Rabbit MQ:订单队列的消息队列。

注意

不建议在没有持久性存储用于生产的情况下,运行有状态容器(例如 Rabbit MQ)。 为简单起见,建议使用托管服务,例如 Azure CosmosDB 或 Azure 服务总线。

  1. 创建名为 aks-store-quickstart.yaml 的文件,并将以下清单复制到其中:

    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: rabbitmq
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: rabbitmq
      template:
        metadata:
          labels:
            app: rabbitmq
        spec:
          nodeSelector:
            "kubernetes.io/os": linux
          containers:
          - name: rabbitmq
            image: mcr.microsoft.com/mirror/docker/library/rabbitmq:3.10-management-alpine
            ports:
            - containerPort: 5672
              name: rabbitmq-amqp
            - containerPort: 15672
              name: rabbitmq-http
            env:
            - name: RABBITMQ_DEFAULT_USER
              value: "username"
            - name: RABBITMQ_DEFAULT_PASS
              value: "password"
            resources:
              requests:
                cpu: 10m
                memory: 128Mi
              limits:
                cpu: 250m
                memory: 256Mi
            volumeMounts:
            - name: rabbitmq-enabled-plugins
              mountPath: /etc/rabbitmq/enabled_plugins
              subPath: enabled_plugins
          volumes:
          - name: rabbitmq-enabled-plugins
            configMap:
              name: rabbitmq-enabled-plugins
              items:
              - key: rabbitmq_enabled_plugins
                path: enabled_plugins
    ---
    apiVersion: v1
    data:
      rabbitmq_enabled_plugins: |
        [rabbitmq_management,rabbitmq_prometheus,rabbitmq_amqp1_0].
    kind: ConfigMap
    metadata:
      name: rabbitmq-enabled-plugins            
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: rabbitmq
    spec:
      selector:
        app: rabbitmq
      ports:
        - name: rabbitmq-amqp
          port: 5672
          targetPort: 5672
        - name: rabbitmq-http
          port: 15672
          targetPort: 15672
      type: ClusterIP
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: order-service
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: order-service
      template:
        metadata:
          labels:
            app: order-service
        spec:
          nodeSelector:
            "kubernetes.io/os": linux
          containers:
          - name: order-service
            image: ghcr.io/azure-samples/aks-store-demo/order-service:latest
            ports:
            - containerPort: 3000
            env:
            - name: ORDER_QUEUE_HOSTNAME
              value: "rabbitmq"
            - name: ORDER_QUEUE_PORT
              value: "5672"
            - name: ORDER_QUEUE_USERNAME
              value: "username"
            - name: ORDER_QUEUE_PASSWORD
              value: "password"
            - name: ORDER_QUEUE_NAME
              value: "orders"
            - name: FASTIFY_ADDRESS
              value: "0.0.0.0"
            resources:
              requests:
                cpu: 1m
                memory: 50Mi
              limits:
                cpu: 75m
                memory: 128Mi
          initContainers:
          - name: wait-for-rabbitmq
            image: busybox
            command: ['sh', '-c', 'until nc -zv rabbitmq 5672; do echo waiting for rabbitmq; sleep 2; done;']
            resources:
              requests:
                cpu: 1m
                memory: 50Mi
              limits:
                cpu: 75m
                memory: 128Mi    
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: order-service
    spec:
      type: ClusterIP
      ports:
      - name: http
        port: 3000
        targetPort: 3000
      selector:
        app: order-service
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: product-service
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: product-service
      template:
        metadata:
          labels:
            app: product-service
        spec:
          nodeSelector:
            "kubernetes.io/os": linux
          containers:
          - name: product-service
            image: ghcr.io/azure-samples/aks-store-demo/product-service:latest
            ports:
            - containerPort: 3002
            resources:
              requests:
                cpu: 1m
                memory: 1Mi
              limits:
                cpu: 1m
                memory: 7Mi
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: product-service
    spec:
      type: ClusterIP
      ports:
      - name: http
        port: 3002
        targetPort: 3002
      selector:
        app: product-service
    ---
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: store-front
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: store-front
      template:
        metadata:
          labels:
            app: store-front
        spec:
          nodeSelector:
            "kubernetes.io/os": linux
          containers:
          - name: store-front
            image: ghcr.io/azure-samples/aks-store-demo/store-front:latest
            ports:
            - containerPort: 8080
              name: store-front
            env: 
            - name: VUE_APP_ORDER_SERVICE_URL
              value: "http://order-service:3000/"
            - name: VUE_APP_PRODUCT_SERVICE_URL
              value: "http://product-service:3002/"
            resources:
              requests:
                cpu: 1m
                memory: 200Mi
              limits:
                cpu: 1000m
                memory: 512Mi
    ---
    apiVersion: v1
    kind: Service
    metadata:
      name: store-front
    spec:
      ports:
      - port: 80
        targetPort: 8080
      selector:
        app: store-front
      type: LoadBalancer
    

    有关 YAML 清单文件的明细,请参阅部署和 YAML 清单

    如果在本地创建并保存 YAML 文件,则可以通过选择“上传/下载文件”按钮并选择本地文件系统中的文件,将清单文件上传到 CloudShell 中的默认目录。

  2. 使用 kubectl apply 命令部署应用程序,并指定 YAML 清单的名称。

    kubectl apply -f aks-store-quickstart.yaml
    

    以下示例输出显示部署和服务:

    deployment.apps/rabbitmq created
    service/rabbitmq created
    deployment.apps/order-service created
    service/order-service created
    deployment.apps/product-service created
    service/product-service created
    deployment.apps/store-front created
    service/store-front created
    

测试应用程序

  1. 使用 kubectl get pods 命令查看已部署的 Pod 的状态。 在继续操作之前,将所有 Pod 都设置为 Running

    kubectl get pods
    
  2. 检查应用商店前端应用程序的公共 IP 地址。 使用带有 --watch 参数的 kubectl get service 命令来监视进度。

    kubectl get service store-front --watch
    

    store-front 服务的 EXTERNAL-IP 输出最初显示为“pending”

    NAME          TYPE           CLUSTER-IP    EXTERNAL-IP   PORT(S)        AGE
    store-front   LoadBalancer   10.0.100.10   <pending>     80:30025/TCP   4h4m
    
  3. EXTERNAL-IP 地址从 pending 更改为实际公共 IP 地址后,请使用 CTRL-C 来停止 kubectl 监视进程。

    以下示例输出显示向服务分配了有效的公共 IP 地址:

    NAME          TYPE           CLUSTER-IP    EXTERNAL-IP    PORT(S)        AGE
    store-front   LoadBalancer   10.0.100.10   20.62.159.19   80:30025/TCP   4h5m
    
  4. 打开 Web 浏览器并转到服务的外部 IP 地址,以查看 Azure 应用商店应用的实际效果。

    Screenshot of AKS Store sample application.

删除群集

如果不打算完成 AKS 教程,请清理不必要的资源以避免产生 Azure 费用。

调用 az group delete 命令移除资源组、容器服务和所有相关资源。

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

注意

AKS 群集是使用系统分配的托管标识创建的,这是本快速入门中使用的默认标识选项。 平台将负责管理此标识,因此你无需手动删除它。

后续步骤

在本快速入门中,你部署了一个 Kubernetes 群集,然后在其中部署了示例多容器应用程序。 此示例应用程序仅用于演示目的,并未展示出 Kubernetes 应用程序的所有最佳做法。 有关使用生产版 AKS 创建完整解决方案的指南,请参阅 AKS 解决方案指南

若要详细了解 AKS 并演练完整的代码到部署示例,请继续阅读 Kubernetes 群集教程。