快速入门:使用 Bicep 扩展性 Kubernetes 提供程序部署 Azure Kubernetes 服务 (AKS) 群集(预览)

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

  • 使用 Bicep 扩展性 Kubernetes 提供程序(预览版)部署 AKS 群集。
  • 运行一个示例多容器应用程序,其中的一组微服务和 Web 前端模拟零售场景。

重要

Bicep Kubernetes 提供程序目前处于预览状态。 可以通过添加以下内容从 Bicep 配置文件 启用该功能:

{
 "experimentalFeaturesEnabled": {
   "extensibility": true,
 }
}

注意

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

开始之前

本快速入门假设读者基本了解 Kubernetes 的概念。 有关详细信息,请参阅 Azure Kubernetes 服务 (AKS) 的 Kubernetes 核心概念

Bicep 是一种特定于域的语言 (DSL),使用声明性语法来部署 Azure 资源。 它提供简明的语法、可靠的类型安全性以及对代码重用的支持。 Bicep 会针对你的 Azure 基础结构即代码解决方案提供最佳创作体验。

  • 若要设置环境以进行 Bicep 开发,请参阅安装 Bicep 工具。 完成这些步骤后,你就获得了 Visual Studio CodeBicep 扩展。 你还获得了最新版本的 Azure CLI 或最新的 Azure PowerShell 模块
  • 若要使用 Bicep 文件创建 AKS 群集,请提供 SSH 公钥。 如果需要此资源,请参阅以下部分。 否则,请跳到查看 Bicep 文件
  • 要部署 Bicep 文件,需要将所部署和访问的资源的访问权限写入到 Microsoft.Resources/deployments 资源类型的所有操作。 例如,若要部署虚拟机,需要 Microsoft.Compute/virtualMachines/writeMicrosoft.Resources/deployments/* 权限。 有关角色和权限的列表,请参阅 Azure 内置角色

创建 SSH 密钥对

若要访问 AKS 节点,请使用通过 ssh-keygen 命令生成的 SSH 密钥对(公钥和私钥)进行连接。 默认情况下,这些文件在 ~/.ssh 目录中创建。 运行 ssh-keygen 命令会覆盖给定位置中同名的任何 SSH 密钥对。

  1. 在浏览器中打开 Power Shell。

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

    # Create an SSH key pair using Azure CLI
    az sshkey create --name "mySSHKey" --resource-group "myResourceGroup"
    
    # Create an SSH key pair using ssh-keygen
    ssh-keygen -t rsa -b 4096
    

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

查阅 Bicep 文件

用于创建 AKS 群集的 Bicep 文件来自 Azure 快速入门模板。 有关更多 AKS 示例,请参阅 AKS 快速入门模板

@description('The name of the Managed Cluster resource.')
param clusterName string = 'aks101cluster'

@description('The location of the Managed Cluster resource.')
param location string = resourceGroup().location

@description('Optional DNS prefix to use with hosted Kubernetes API server FQDN.')
param dnsPrefix string

@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)
param osDiskSizeGB int = 0

@description('The number of nodes for the cluster.')
@minValue(1)
@maxValue(50)
param agentCount int = 3

@description('The size of the Virtual Machine.')
param agentVMSize string = 'standard_d2s_v3'

@description('User name for the Linux Virtual Machines.')
param linuxAdminUsername string

@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\'')
param sshRSAPublicKey string

resource aks 'Microsoft.ContainerService/managedClusters@2022-05-02-preview' = {
  name: clusterName
  location: location
  identity: {
    type: 'SystemAssigned'
  }
  properties: {
    dnsPrefix: dnsPrefix
    agentPoolProfiles: [
      {
        name: 'agentpool'
        osDiskSizeGB: osDiskSizeGB
        count: agentCount
        vmSize: agentVMSize
        osType: 'Linux'
        mode: 'System'
      }
    ]
    linuxProfile: {
      adminUsername: linuxAdminUsername
      ssh: {
        publicKeys: [
          {
            keyData: sshRSAPublicKey
          }
        ]
      }
    }
  }
}

output controlPlaneFQDN string = aks.properties.fqdn

在 Bicep 文件中定义的资源是 Microsoft.ContainerService/managedClusters

将文件的副本作为 main.bicep 另存到本地计算机。

添加应用程序定义

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

Screenshot of Azure Store sample architecture.

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

注意

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

  1. main.bicep 所在的文件夹中创建名为 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 清单

  2. 在 Visual Studio Code 中打开 main.bicep

  3. Ctrl+Shift+P 打开命令面板

  4. 搜索 bicep,然后选择“Bicep:导入 Kubernetes 清单”。

    Screenshot of Visual Studio Code import Kubernetes Manifest.

  5. 从提示中选择“aks-store-quickstart.yaml”。 此过程在同一文件夹中创建文件 aks-store-quickstart.bicep

  6. 打开 main.bicep 并在文件末尾添加以下 Bicep 以引用新创建的 aks-store-quickstart.bicep 模块:

    module kubernetes './aks-store-quickstart.bicep' = {
      name: 'buildbicep-deploy'
      params: {
        kubeConfig: aks.listClusterAdminCredential().kubeconfigs[0].value
      }
    }
    
  7. 同时保存 main.bicepaks-store-quickstart.bicep

部署 Bicep 文件

  1. 使用 az group create 命令创建 Azure 资源组。

    az group create --name myResourceGroup --location eastus
    
  2. 使用 az deployment group create 命令部署 Bicep 文件。

    az deployment group create --resource-group myResourceGroup --template-file main.bicep --parameters clusterName=<cluster-name> dnsPrefix=<dns-previs> linuxAdminUsername=<linux-admin-username> sshRSAPublicKey='<ssh-key>'
    

在命令中提供以下值:

  • 群集名称:输入 AKS 群集的唯一名称,例如 myAKSCluster
  • DNS 前缀:输入群集的唯一 DNS 前缀,例如 myakscluster
  • Linux 管理员用户名:输入一个用户名用于通过 SSH 进行连接,例如 azureuser
  • SSH RSA 公钥:复制并粘贴 SSH 密钥对的 public 部分(默认为 ~/.ssh/id_rsa.pub 的内容)。

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

验证 Bicep 部署

  1. 登录 Azure 门户

  2. 在 Azure 门户菜单上或从主页中,导航到你的 AKS 群集

  3. 在“Kubernetes 资源”下,选择“服务和入口”

  4. 找到“store-front”服务,并复制“外部 IP”的值。

  5. 打开 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 并演练完整的代码到部署示例,请继续阅读 Kubernetes 群集教程。