Azure- 使用 Helm 管理应用程序和包

本实验来自于使用 Helm 管理应用程序和包

实验环境

在此实验中,将使用 HELM 为测试部署安装一个 AKS 群集。 使用脚本来创建和配置 Azure Kubernetes 服务 (AKS) 群集。

此脚本执行以下配置步骤:

  • 选择要与此模块的练习一起使用的订阅,并将其设置为所有已部署资源的默认订阅。
  • 使用 Azure CLI 创建 Azure Kubernetes 服务群集。
  • 配置默认的 Kubernetes NGINX 入口控制器和负载均衡器。
  • 从 GitHub 存储库克隆示例Web 应用和 Helm chart。
  • 在/home/user/clouddrive/mslearn-aks/create-aks-exports.txt
    中捕获所有配置值,以方便引用。

运行部署脚本

  1. 使用 bash 部署脚本,该脚本使用以下参数部署新群集:
参数 描述
-s 标识要使用的订阅 ID。
-n 标识用于在此模块的上下文中创建群集的 AKS 群集名称和资源组。
–use-acr 允许脚本配置名为 mslearn-kubernetes-acr 的默认 ACR。 默认值为 false。
–install-dot-net 允许脚本安装 .NET Core SDK。 默认值设置为 false。

脚本地址:https://raw.githubusercontent.com/MicrosoftDocs/mslearn-aks/main/infrastructure/setup/setup.sh

#!/bin/bash

# Hi!
# If you're reading this, you're probably interested in what's going on within this script. 
# We've provided what we hope are useful comments inline, as well as color-coded relevant 
# shell output. We hope it's useful for you, but if you have any questions or suggestions
# please open an issue on https:/github.com/MicrosoftDocs/mslearn-aks.

while [ "$1" != "" ]; do
    case $1 in
        -s | --subscription)            shift
                                        clusterSubs=$1
                                        ;;
        -n | --name)                    shift
                                        moduleName=$1
                                        ;;
        -a | --use-acr)                 shift
                                        useACR=$1
                                        ;;
        -i | --install-dot-net)         shift
                                        installDotNet=$1
                                        ;;
             * )                        echo "Invalid param: $1"
                                        exit 1
    esac
    shift
done

if [ -z "$clusterSubs" ]; then
     echo "${newline}${errorStyle}ERROR: Subscription is mandatory. Use -s to set it.$clusterSubs.${defaultTextStyle}${newline}"
     listSubsCommand="az account list -o table"
     $listSubsCommand
     echo "${newline}Use one of the ${azCliCommandStyle}SubscriptionId${defaultTextStyle} above to run the command${newline}"
     return 1
fi

if [ -z "$moduleName" ]; then
     echo "${newline}${errorStyle}ERROR: Cluster name is mandatory. Use -n to set it.${defaultTextStyle}${newline}"
     return 1
fi

## Start
cd ~

# dotnet SDK version
declare -x dotnetSdkVersion="3.1.302"

# Module name
if [ -z "$moduleName" ]; then
    declare moduleName="mslearn-aks"
fi

# Any other declarations we need
declare -x gitUser="MicrosoftDocs"
declare -x gitBranch="main"
declare initScript=https://raw.githubusercontent.com/$gitUser/mslearn-aks/$gitBranch/infrastructure/setup/init-env.sh
declare suppressAzureResources=false
declare rootLocation=~/clouddrive
declare editorHomeLocation=$rootLocation/mslearn-aks

if [ -d "$rootLocation/mslearn-aks" ]; then
    echo "$rootLocation/mslearn-aks/ already exists!"
    echo " "
    echo "Before running this script, please remove or rename the existing $rootLocation/mslearn-aks/ directory as follows:"
    echo "Remove: rm -r $rootLocation/mslearn-aks/"
    echo "Rename: mv $rootLocation/mslearn-aks/ ~/clouddrive/new-name-here/"
    echo " "
    return 1
else
    # Backup .bashrc
    cp ~/.bashrc ~/.bashrc.bak.$moduleName

    if [ -z "$installDotNet" ]; then
        declare installDotNet="false"
    fi

    # Grab and run init-env.sh
    . <(wget -q -O - $initScript)

    # Download and build
    downloadAndBuild

    # Set location to ~/clouddrive
    cd $editorHomeLocation

    # Run mslearn-aks quickstart to deploy to AKS
    $editorHomeLocation/infrastructure/deploy/k8s/quickstart.sh --subscription $clusterSubs --resource-group $resourceGroupName -n $moduleName --location westus

    # Create ACR resource
    if [ -z "$useACR" ]; then
        declare useACR="false"
    fi

    if  ! [ -z "$useACR" ] && [ $useACR == true ]; then
        $editorHomeLocation/infrastructure/deploy/k8s/create-acr.sh --subscription $clusterSubs --resource-group $resourceGroupName --aks-name $moduleName --acr-name mslearn-aks-acr --location westus
    fi

    # Display information to use
    echo "Azure Container Registry Information"
    echo "=================================================================================="
    cat ~/clouddrive/mslearn-aks/create-acr-exports.txt
    echo "=================================================================================="
    echo 
    echo
    echo "Azure Container Kubernetes Cluster Information"
    echo "=================================================================================="
    cat ~/clouddrive/mslearn-aks/create-aks-exports.txt
    echo "=================================================================================="
fi

#Reset variables
declare clusterSubs=""
declare moduleName=""
declare useACR="false"
declare installDotNet="false"
  1. 在 Azure Cloud Shell 中运行以下命令以安装运行环境。
SubscriptionId=$(az account list --query '[0].id' -o tsv)
. <(wget -q -O - https://raw.githubusercontent.com/MicrosoftDocs/mslearn-aks/main/infrastructure/setup/setup.sh ) -s $SubscriptionId -n learn-helm-deploy-aks --use-acr false --install-dot-net false

执行结果

izhao_yiyi@Azure:~$ SubscriptionId=$(az account list --query '[0].id' -o tsv)
izhao_yiyi@Azure:~$ . <(wget -q -O - https://raw.githubusercontent.com/MicrosoftDocs/mslearn-aks/main/infrastructure/setup/setup.sh ) -s $SubscriptionId -n learn-helm-deploy-aks --use-acr false --install-dot-net false
WARNING!!! It appears you aren't currently running in a Microsoft Learn sandbox. Any Azure resources provisioned by this script will result in charges to your Azure subscription.
Using Azure resource group learn-helm-deploy-aks-rg.

Downloading code...
++ wget -q -O - https://raw.githubusercontent.com/MicrosoftDocs/mslearn-aks/main/infrastructure/setup/sparsecheckout.sh
++ bash -s infrastructure/deploy/ modules/learn-helm-deploy-aks/src/
Updating origin
remote: Enumerating objects: 302, done.
remote: Counting objects: 100% (168/168), done.
remote: Compressing objects: 100% (157/157), done.
remote: Total 302 (delta 68), reused 20 (delta 3), pack-reused 134
Receiving objects: 100% (302/302), 381.59 KiB | 838.00 KiB/s, done.
Resolving deltas: 100% (90/90), done.
From https://github.com/MicrosoftDocs/mslearn-aks
 * [new branch]      main        -> origin/main
 * [new branch]      oct-refresh -> origin/oct-refresh
 * [new branch]      test        -> origin/test

Switching to subscription 14adb214-7b29-422a-ac8a-df2af1e51201...
Switching to subscription 14adb214-7b29-422a-ac8a-df2af1e51201...
Creating resource group learn-helm-deploy-aks-rg in location westus...
 > az group create -n learn-helm-deploy-aks-rg -l westus --output none

Creating AKS cluster "learn-helm-deploy-aks" in resource group "learn-helm-deploy-aks-rg" and location "westus"...
 > az aks create -n learn-helm-deploy-aks -g learn-helm-deploy-aks-rg --node-count 1 --node-vm-size Standard_B2s --vm-set-type VirtualMachineScaleSets -l westus --enable-managed-identity --generate-ssh-keys -o json
WARNING: The behavior of this command has been altered by the following extension: aks-preview

AKS cluster created.

Getting credentials for AKS...
The behavior of this command has been altered by the following extension: aks-preview
Merged "learn-helm-deploy-aks" as current context in /home/izhao_yiyi/.kube/config

Installing NGINX ingress controller
namespace/nginx-ingress created
serviceaccount/nginx-ingress created
clusterrole.rbac.authorization.k8s.io/nginx-ingress created
clusterrolebinding.rbac.authorization.k8s.io/nginx-ingress created
secret/default-server-secret created
configmap/nginx-config created
ingressclass.networking.k8s.io/nginx created
deployment.apps/nginx-ingress created
service/nginx-ingress created

Getting load balancer public IP
 > az aks list --query "[?name=='learn-helm-deploy-aks'&&resourceGroup=='learn-helm-deploy-aks-rg'].nodeResourceGroup" -o tsv
Waiting for the Load Balancer IP address - Ctrl+C to cancel...
Waiting for the Load Balancer IP address - Ctrl+C to cancel...
Waiting for the Load Balancer IP address - Ctrl+C to cancel...
Assigned IP address: 104.42.158.195

Nginx ingress controller installed.
Azure Container Registry Information
==================================================================================
cat: /home/izhao_yiyi/clouddrive/mslearn-aks/create-acr-exports.txt: No such file or directory
==================================================================================


Azure Container Kubernetes Cluster Information
==================================================================================
export CLUSTER_NAME=learn-helm-deploy-aks
export CLUSTER_SUBS=14adb214-7b29-422a-ac8a-df2af1e51201
export CLUSTER_RG=learn-helm-deploy-aks-rg
export CLUSTER_LOCATION=westus
export CLUSTER_AKSNODERG=MC_learn-helm-deploy-aks-rg_learn-helm-deploy-aks_westus
export CLUSTER_LBIP=104.42.158.195
export LEARN_REGISTRY=learn-aks-registry
==================================================================================

安装 Helm chart

在此实验中,将 Helm 存储库添加到 Helm 客户端,并将 ASP.NET Core 网站安装到 Azure Kubernetes 服务群集。

提取 Helm chart

  1. 在 Azure Cloud Shell 中,将 Azure 市场 Helm 存储库添加到 Helm 客户端。 可以通过此存储库访问许多预配置的 Helm chart。

helm repo add azure-marketplace https://marketplace.azurecr.io/helm/v1/repo

  1. 运行 helm repo list 命令来确认新添加的存储库。

helm repo list

上述命令返回以下输出的结果:

izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm repo add azure-marketplace https://marketplace.azurecr.io/helm/v1/repo
"azure-marketplace" has been added to your repositories
izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm version
version.BuildInfo{Version:"v3.4.0", GitCommit:"7090a89efc8a18f3d8178bf47d2462450349a004", GitTreeState:"clean", GoVersion:"go1.14.10"}
izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm repo ls
NAME                    URL
azure-marketplace       https://marketplace.azurecr.io/helm/v1/repo
  1. 运行 helm search repo 命令,以搜索 azure-marketplace/aspnet-core chart

helm search repo aspnet

izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm search repo aspnet
NAME                            CHART VERSION   APP VERSION     DESCRIPTION
azure-marketplace/aspnet-core   2.0.1           3.1.21          ASP.NET Core is an open-source framework create...

部署 Helm chart

  1. 使用 helm install 命令部署 ASP.NET Core Helm chart。

helm install aspnet-webapp azure-marketplace/aspnet-core

此命令返回以下输出的结果:

izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm install aspnet-webapp azure-marketplace/aspnet-core
NAME: aspnet-webapp
LAST DEPLOYED: Thu Dec  9 14:31:00 2021
NAMESPACE: default
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
CHART NAME: aspnet-core
CHART VERSION: 2.0.1
APP VERSION: 3.1.21

** Please be patient while the chart is being deployed **

ASP.NET Core can be accessed through the following DNS name from within your cluster:

    aspnet-webapp-aspnet-core.default.svc.cluster.local (port )

To access ASP.NET Core from outside the cluster execute the following commands:

1. Get the ASP.NET Core URL by running these commands:

    export SERVICE_PORT=$(kubectl get --namespace default -o jsonpath="{.spec.ports[0].port}" services aspnet-webapp-aspnet-core)
    kubectl port-forward --namespace default svc/aspnet-webapp-aspnet-core ${SERVICE_PORT}:${SERVICE_PORT} &
    echo "http://127.0.0.1:${SERVICE_PORT}"

2. Access ASP.NET Core using the obtained URL.
  1. 使用 helm list 命令来列出所有 Helm release。
 izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm ls
NAME            NAMESPACE       REVISION        UPDATED                                 STATUS          CHART                   APP VERSION
aspnet-webapp   default         1               2021-12-09 14:31:00.966036159 +0000 UTC deployed        aspnet-core-2.0.1       3.1.21

每次对发布进行更改时,修订号version都将递增。

  1. Helm 允许使用 helm get manifest 命令提取与每个发布相关的清单信息:
izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm get manifest aspnet-webapp
---
# Source: aspnet-core/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: aspnet-webapp-aspnet-core
  labels:
    app.kubernetes.io/name: aspnet-core
    helm.sh/chart: aspnet-core-2.0.1
    app.kubernetes.io/instance: aspnet-webapp
    app.kubernetes.io/managed-by: Helm
  annotations:
---
# Source: aspnet-core/templates/svc.yaml
apiVersion: v1
kind: Service
metadata:
  name: aspnet-webapp-aspnet-core
  labels:
    app.kubernetes.io/name: aspnet-core
    helm.sh/chart: aspnet-core-2.0.1
    app.kubernetes.io/instance: aspnet-webapp
    app.kubernetes.io/managed-by: Helm
  annotations:
spec:
  type: ClusterIP
  ports:
    - name: http
      port: 80
      targetPort: http
      nodePort: null
  selector:
    app.kubernetes.io/name: aspnet-core
    app.kubernetes.io/instance: aspnet-webapp
---
# Source: aspnet-core/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: aspnet-webapp-aspnet-core
  labels:
    app.kubernetes.io/name: aspnet-core
    helm.sh/chart: aspnet-core-2.0.1
    app.kubernetes.io/instance: aspnet-webapp
    app.kubernetes.io/managed-by: Helm
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: aspnet-core
      app.kubernetes.io/instance: aspnet-webapp
  strategy:
    type: RollingUpdate
  template:
    metadata:
      labels:
        app.kubernetes.io/name: aspnet-core
        helm.sh/chart: aspnet-core-2.0.1
        app.kubernetes.io/instance: aspnet-webapp
        app.kubernetes.io/managed-by: Helm
    spec:

      automountServiceAccountToken: true
      serviceAccountName: aspnet-webapp-aspnet-core
      affinity:
        podAffinity:

        podAntiAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - podAffinityTerm:
                labelSelector:
                  matchLabels:
                    app.kubernetes.io/name: aspnet-core
                    app.kubernetes.io/instance: aspnet-webapp
                namespaces:
                  - "default"
                topologyKey: kubernetes.io/hostname
              weight: 1
        nodeAffinity:

      initContainers:
        - name: clone-repository
          image: marketplace.azurecr.io/bitnami/git:2.33.0-debian-10-r81
          imagePullPolicy: "IfNotPresent"
          command:
            - /bin/bash
            - -ec
            - |
              [[ -f "/opt/bitnami/scripts/git/entrypoint.sh" ]] && source "/opt/bitnami/scripts/git/entrypoint.sh"
              git clone https://github.com/dotnet/AspNetCore.Docs.git --branch main /repo
          volumeMounts:
            - name: repo
              mountPath: /repo
        - name: dotnet-publish
          image: marketplace.azurecr.io/bitnami/dotnet-sdk:3.1.414-debian-10-r26
          imagePullPolicy: "IfNotPresent"
          workingDir: /repo
          command:
            - /bin/bash
            - -ec
            - |
              cd aspnetcore/fundamentals/servers/kestrel/samples/3.x/KestrelSample
              dotnet publish -o /app
          volumeMounts:
            - name: app
              mountPath: /app
            - name: repo
              mountPath: /repo
      containers:
        - name: aspnet-core
          image: marketplace.azurecr.io/bitnami/aspnet-core:3.1.21-debian-10-r0
          imagePullPolicy: "IfNotPresent"
          workingDir: /app
          command:
            - dotnet
            - KestrelSample.dll
          env:
            - name: ASPNETCORE_URLS
              value: "http://+:8080"
          ports:
            - name: http
              containerPort: 8080
          livenessProbe:
            tcpSocket:
              port: http
            initialDelaySeconds: 10
            periodSeconds: 20
            timeoutSeconds: 1
            successThreshold: 1
            failureThreshold: 6
          readinessProbe:
            tcpSocket:
              port: http
            initialDelaySeconds: 10
            periodSeconds: 20
            timeoutSeconds: 1
            successThreshold: 1
            failureThreshold: 6
          resources:
            limits: {}
            requests: {}
          volumeMounts:
            - name: app
              mountPath: /app
      volumes:
        - name: app
          emptyDir: {}
        - name: repo
          emptyDir: {}

chart的 templates 文件夹中有三个 YAML 文件。

  • ServiceAccount
  • 服务svc
  • 部署deployment

这些文件是根据chart的可用模板和 values.yaml 文件中可用的值的组合呈现的。

  1. 通过运行/使用 kubectl 命令验证是否已部署 Pod
izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ kubectl get all
NAME                                            READY   STATUS    RESTARTS   AGE
pod/aspnet-webapp-aspnet-core-676b9cfdd-xm2ss   1/1     Running   0          3m22s

NAME                                TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
service/aspnet-webapp-aspnet-core   ClusterIP   10.0.116.227   <none>        80/TCP    3m23s
service/kubernetes                  ClusterIP   10.0.0.1       <none>        443/TCP   12m

NAME                                        READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/aspnet-webapp-aspnet-core   1/1     1            1           3m23s

NAME                                                  DESIRED   CURRENT   READY   AGE
replicaset.apps/aspnet-webapp-aspnet-core-676b9cfdd   1         1         1       3m23s
  1. 删除 Helm 发布
    使用 helm delete 命令删除 Helm 发布
izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm delete aspnet-webapp
release "aspnet-webapp" uninstalled

使用设置的值安装 Helm chart

  1. 可以通过传递值参数或自己的 values.yaml 文件来替代 Helm chart的值。

现在,使用 --set 参数的情况下运行 helm install,将部署模板的 replicaCount 设置为五个副本。

izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm install --set replicaCount=5 aspnet-webapp azure-marketplace/aspnet-core
NAME: aspnet-webapp
LAST DEPLOYED: Thu Dec  9 14:39:09 2021
NAMESPACE: default
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
CHART NAME: aspnet-core
CHART VERSION: 2.0.1
APP VERSION: 3.1.21

** Please be patient while the chart is being deployed **

ASP.NET Core can be accessed through the following DNS name from within your cluster:

    aspnet-webapp-aspnet-core.default.svc.cluster.local (port )

To access ASP.NET Core from outside the cluster execute the following commands:

1. Get the ASP.NET Core URL by running these commands:

    export SERVICE_PORT=$(kubectl get --namespace default -o jsonpath="{.spec.ports[0].port}" services aspnet-webapp-aspnet-core)
    kubectl port-forward --namespace default svc/aspnet-webapp-aspnet-core ${SERVICE_PORT}:${SERVICE_PORT} &
    echo "http://127.0.0.1:${SERVICE_PORT}"

2. Access ASP.NET Core using the obtained URL.

通过运行 kubectl get pods 命令验证

izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ kubectl get po
NAME                                        READY   STATUS    RESTARTS   AGE
aspnet-webapp-aspnet-core-676b9cfdd-7542j   1/1     Running   0          4m11s
aspnet-webapp-aspnet-core-676b9cfdd-bxf9w   1/1     Running   0          4m11s
aspnet-webapp-aspnet-core-676b9cfdd-cm79p   1/1     Running   0          4m11s
aspnet-webapp-aspnet-core-676b9cfdd-pjgl7   1/1     Running   0          4m11s
aspnet-webapp-aspnet-core-676b9cfdd-qg8nd   1/1     Running   0          4m11s

2.使用 helm delete 命令删除 Helm chart。 此命令将删除工作负荷的发布和所有副本。

izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ helm delete aspnet-webapp
release "aspnet-webapp" uninstalled

管理 Helm 发布

在此练习中,自定义现有的 Helm chart来安装、升级、回滚和删除 Helm 发布。

查看 Helm chart文件夹结构

之前从 Azure 市场安装的 aspnet-core Helm chart作为基础来安装 .NET Core Blazor Server 应用。 在 AKS 群集创建中已下载了应用程序的源代码,这些源代码位于 ~clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src/drone-webapp 文件夹中。

  1. 列出 $HOME/.cache/helm/repository 文件夹的内容以查找 aspnet-core-xxx.tgz 文件。
izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ ls $HOME/.cache/helm/repository -l
total 5096
-rw-r--r-- 1 izhao_yiyi izhao_yiyi   32351 Dec  9 14:39 aspnet-core-2.0.1.tgz
-rw-r--r-- 1 izhao_yiyi izhao_yiyi    1440 Dec  9 14:28 azure-marketplace-charts.txt
-rw-r--r-- 1 izhao_yiyi izhao_yiyi 5181359 Dec  9 14:28 azure-marketplace-index.yaml

从存储库安装的所有 Helm chart都缓存在此文件夹中。

  1. 通过递归列出 drone-webapp-chart 文件夹的所有内容,检查现有的 Helm chart
    对于本实验,chart已经解压缩,位于 ~clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src/drone-webapp-chart 文件夹中。
izhao_yiyi@Azure:~/clouddrive/mslearn-aks$ cd ~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ find drone-webapp-chart/ -print
drone-webapp-chart/
drone-webapp-chart/.helmignore
drone-webapp-chart/Chart.yaml
drone-webapp-chart/templates
drone-webapp-chart/templates/deployment.yaml
drone-webapp-chart/templates/extra-list.yaml
drone-webapp-chart/templates/health-ingress.yaml
drone-webapp-chart/templates/hpa.yaml
drone-webapp-chart/templates/ingress.yaml
drone-webapp-chart/templates/NOTES.txt
drone-webapp-chart/templates/pdb.yaml
drone-webapp-chart/templates/service.yaml
drone-webapp-chart/templates/serviceaccount.yaml
drone-webapp-chart/templates/tls-secret.yaml
drone-webapp-chart/templates/_helpers.tpl
drone-webapp-chart/values.yaml

以下组件为核心:

  • Chart.yaml 文件 (drone-webapp-chart/Chart.yaml)
  • values.yaml 文件 (drone-webapp-chart/values.yaml)
  • templates/ 文件夹中的许多模板 (drone-webapp-chart/templates)
  1. 使用内置的 Cloud Shell 编辑器打开 drone-webapp-chart/Chart.yaml 以查看chart的依赖项。
apiVersion: v2
appVersion: 0.0.1
description: ASP.NET Core is an open-source framework created by Microsoft for building
  cloud-enabled, modern applications.
home: https://dotnet.microsoft.com/apps/aspnet
icon: https://bitnami.com/assets/stacks/aspnet-core/img/aspnet-core-stack-220x234.png
keywords:
- asp.net
- dotnet
maintainers:
- email: [email protected]
- name: Bitnami
name: drone-tracker
sources:
- https://github.com/bitnami/bitnami-docker-aspnet-core
annotations:
 category: DeveloperTools
version: 1.3.21
dependencies:
  - name: common
    version: 1.10.3
    repository: https://marketplace.azurecr.io/helm/v1/repo
    tags:
      - bitnami-common
  1. 运行 helm dependency build 命令可下载和更新全部的chart依赖项
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ helm dependency build ./drone-webapp-chart
Hang tight while we grab the latest from your chart repositories...
...Successfully got an update from the "azure-marketplace" chart repository
Update Complete. ⎈Happy Helming!⎈
Saving 1 charts
Downloading common from repo https://marketplace.azurecr.io/helm/v1/repo
Deleting outdated charts
  1. 查看 drone-webapp-chart 文件夹中的文件,以了解 Helm 下载的内容
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ find drone-webapp-chart/ -print
drone-webapp-chart/
drone-webapp-chart/.helmignore
drone-webapp-chart/Chart.lock
drone-webapp-chart/Chart.yaml
drone-webapp-chart/charts
drone-webapp-chart/charts/common-1.10.3.tgz
drone-webapp-chart/templates
drone-webapp-chart/templates/deployment.yaml
drone-webapp-chart/templates/extra-list.yaml
drone-webapp-chart/templates/health-ingress.yaml
drone-webapp-chart/templates/hpa.yaml
drone-webapp-chart/templates/ingress.yaml
drone-webapp-chart/templates/NOTES.txt
drone-webapp-chart/templates/pdb.yaml
drone-webapp-chart/templates/service.yaml
drone-webapp-chart/templates/serviceaccount.yaml
drone-webapp-chart/templates/tls-secret.yaml
drone-webapp-chart/templates/_helpers.tpl
drone-webapp-chart/values.yaml

现在,charts/ 文件夹中有一个名为 common 的已更新子chart。 可以提取 common-1.10.3.tgz 包的内容

查看chart values.yaml 文件

aspnet-core Helm chart具有一组广泛的配置选项,可用于管理云原生 Web 应用的总体部署。 查看 values.yaml 的内容以获取部署概述非常有用。

在 Cloud Shell 编辑器中打开 values.yaml。

vim ./drone-webapp-chart/values.yaml

此文件中有许多需要关注的点。 这里查看两个节以及它们如何影响最终的已部署应用。

搜索 image 值以查看哪个图像用于 Web 应用。

...
image:
  registry: docker.io
  repository: bitnami/aspnet-core
  tag: 3.1.21-debian-10-r0
  pullPolicy: IfNotPresent
...

注意 bitnami/aspnet-core Docker 映像。 此映像是应用的基础映像,包含 ASP.NET Core 安装。

搜索 appFromExternalRepo 值。 将使用这些值生成 deployment.yaml 清单文件。

appFromExternalRepo:
  enabled: true
  clone:
    image:
      registry: docker.io
      repository: bitnami/git
      tag: 2.33.0-debian-10-r28
      pullPolicy: IfNotPresent
      pullSecrets: []
    repository: https://github.com/MicrosoftDocs/mslearn-aks.git
    revision: main
    extraVolumeMounts: []
  publish:
    image:
      registry: docker.io
      repository: bitnami/dotnet-sdk
      tag: 3.1.412-debian-10-r33
      pullPolicy: IfNotPresent
      pullSecrets: []
    subFolder: modules/learn-helm-deploy-aks/src/drone-webapp
    extraFlags: []
    startCommand: ["dotnet", "drone-webapp.dll"]

此节指定了要注意的几个项。

  • bitnami/git 映像

  • bitnami/dotnet-sdk 映像

  • GitHub 存储库 https://github.com/MicrosoftDocs/mslearn-aks.git

  • 应用源代码存储库子文件夹 modules/learn-helm-deploy-aks/src/drone-webapp

这些值中的每一个都在 templates/deployment.yaml 文件中使用。

接下来,在 values.yaml 文件中搜索 ingress 值。 使用这些值生成 ingress.yaml 清单文件。

ingress:
  enabled: true
  pathType: ImplementationSpecific
  hostname: aspnet-core.local
  path: /
  annotations: {}
  tls: false
  secrets: []

此允许你配置最终入口文件的许多方面。 对于本实验,只需使用 ingress.enabled 值。

查看 deployment.yaml 和 ingress.yaml 模板文件

values.yaml 文件中的值与chart的 templates/ 文件夹中的模板结合使用,以创建最终的清单文件。

  1. 在 Cloud Shell 编辑器中打开 templates/deployment.yaml。

vim ./drone-webapp-chart/templates/deployment.yaml

apiVersion: {{ include "common.capabilities.deployment.apiVersion" . }}
kind: Deployment
metadata:
  ...
spec:
  replicas: {{ .Values.replicaCount }}
  ...
      initContainers:
        {{- if .Values.appFromExternalRepo.enabled }}
        - name: clone-repository
          image: {{ include "aspnet-core.git.image" . }}
          imagePullPolicy: {{ .Values.appFromExternalRepo.clone.image.pullPolicy | quote }}
          command:
            - /bin/bash
            - -ec
            - |
              [[ -f "/opt/bitnami/scripts/git/entrypoint.sh" ]] && source "/opt/bitnami/scripts/git/entrypoint.sh"
              git clone {{ .Values.appFromExternalRepo.clone.repository }} --branch {{ .Values.appFromExternalRepo.clone.revision }} /repo
          volumeMounts:
            - name: repo
              mountPath: /repo
        - name: dotnet-publish
          image: {{ include "aspnet-core.sdk.image" . }}
          imagePullPolicy: {{ .Values.appFromExternalRepo.publish.image.pullPolicy | quote }}
          workingDir: /repo
          command:
            - /bin/bash
            - -ec
            - |
              cd {{ .Values.appFromExternalRepo.publish.subFolder }}
              dotnet publish -o /app {{ .Values.appFromExternalRepo.publish.extraFlags | join " " }}
          volumeMounts:
            - name: app
              mountPath: /app
            - name: repo
              mountPath: /repo
        {{- end }}
        {{- if .Values.initContainers }}
        {{- include "common.tplvalues.render" (dict "value" .Values.initContainers "context" $) | nindent 8 }}
        {{- end }}
      {{- end }}
      ...

注意,此文件具有部署清单的结构,但最终哪些信息进入文件取决于 values.yaml 文件中的值和模板控制流逻辑。

例如,此部署的 spec.replicas 是由 {{ .Values.replicaCount }} 定义的,容器如何初始化取决于 {{- if .Values.appFromExternalRepo.enabled }} 语句中的 .Values.appFromExternalRepo.enabled 值。

然后,本节的其余部分会使用 Git 映像和存储库值来克隆存储库并构建 Web 应用。

  1. 在 Cloud Shell 编辑器中打开 templates/ingress.yaml。

vim ./drone-webapp-chart/templates/ingress.yaml

{{- if .Values.ingress.enabled -}}
apiVersion: {{ include "common.capabilities.ingress.apiVersion" . }}
kind: Ingress
metadata:
  name: {{ include "aspnet-core.fullname" . }}
  labels: {{- include "common.labels.standard" . | nindent 4 }}
    ...
  annotations:
    ...
spec:
  ...
{{- end }}

注意入口清单如何依赖于 {{- if .Values.ingress.enabled -}} 语句。

部署 Helm chart

现在可以部署 Web 应用了。

  1. 使用 helm install 命令部署 drone-webapp Helm chart。
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ helm install drone-webapp ./drone-webapp-chart
NAME: drone-webapp
LAST DEPLOYED: Thu Dec  9 14:59:26 2021
NAMESPACE: default
STATUS: deployed
REVISION: 1
TEST SUITE: None
NOTES:
** Please be patient while the chart is being deployed **

ASP.NET Core can be accessed through the following DNS name from within your cluster:

    drone-webapp-aspnet-core.default.svc.cluster.local (port 80)

To access ASP.NET Core from outside the cluster execute the following commands:

1. Get the ASP.NET Core URL and associate its hostname to your cluster external IP:

   export CLUSTER_IP=$(minikube ip) # On Minikube. Use: `kubectl cluster-info` on others K8s clusters
   echo "ASP.NET Core URL: http://aspnet-core.local"
   echo "$CLUSTER_IP  aspnet-core.local" | sudo tee -a /etc/hosts

2. Access ASP.NET Core using the obtained URL.

查看安装过程

izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ kubectl get po -w
NAME                                        READY   STATUS     RESTARTS   AGE
drone-webapp-aspnet-core-54894f544b-7j72z   0/1     Init:0/2   0          13s
drone-webapp-aspnet-core-54894f544b-7j72z   0/1     Init:ErrImagePull   0          72s
drone-webapp-aspnet-core-54894f544b-7j72z   0/1     Init:ImagePullBackOff   0          84s
drone-webapp-aspnet-core-54894f544b-7j72z   0/1     Init:0/2                0          94s
drone-webapp-aspnet-core-54894f544b-7j72z   0/1     Init:1/2                0          95s
drone-webapp-aspnet-core-54894f544b-7j72z   0/1     Init:1/2                0          2m20s
drone-webapp-aspnet-core-54894f544b-7j72z   0/1     PodInitializing         0          2m28s
drone-webapp-aspnet-core-54894f544b-7j72z   0/1     Running                 0          3m6s
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ kubectl get po
NAME                                        READY   STATUS    RESTARTS   AGE
drone-webapp-aspnet-core-54894f544b-7j72z   1/1     Running   0          3m25s
  1. 在 Web 应用运行后,在浏览器中打开 die 群集的负载均衡器 IP 地址,以查看正在运行的 Web 应用。 列出 create-aks-exports.txt 文件的内容以查找负载均衡器的 IP 地址。
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ cat ~/clouddrive/mslearn-aks/create-aks-exports.txt
export CLUSTER_NAME=learn-helm-deploy-aks
export CLUSTER_SUBS=14adb214-7b29-422a-ac8a-df2af1e51201
export CLUSTER_RG=learn-helm-deploy-aks-rg
export CLUSTER_LOCATION=westus
export CLUSTER_AKSNODERG=MC_learn-helm-deploy-aks-rg_learn-helm-deploy-aks_westus
export CLUSTER_LBIP=104.42.158.195
export LEARN_REGISTRY=learn-aks-registry

升级 Helm 发布

如果开发团队更新了 Web 应用的源代码。 若要部署新版本,需使用 helm upgrade 命令来创建对应用的最新更改的增量。

  1. 第一步是使用 helm list 命令列出所有 Helm 部署。
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ helm ls
NAME            NAMESPACE       REVISION        UPDATED                                 STATUS          CHART                   APP VERSION
drone-webapp    default         1               2021-12-09 14:59:26.723136514 +0000 UTC deployed        aspnet-core-1.3.18      0.0.1
  1. 运行 helm history 命令,查看有关 drone-webapp 的历史记录信息
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ helm history drone-webapp
REVISION        UPDATED                         STATUS          CHART                   APP VERSION     DESCRIPTION
1               Thu Dec  9 14:59:26 2021        deployed        aspnet-core-1.3.18      0.0.1           Install complete
  1. 打开 Chart.yaml 文件,更新应用程序的版本号。
    将 appVersion 编号更新为版本 0.0.2,并运行以下 helm upgrade 命令。
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ helm upgrade drone-webapp ./drone-webapp-chart
Release "drone-webapp" has been upgraded. Happy Helming!
NAME: drone-webapp
LAST DEPLOYED: Thu Dec  9 15:08:18 2021
NAMESPACE: default
STATUS: deployed
REVISION: 2
TEST SUITE: None
NOTES:
** Please be patient while the chart is being deployed **

ASP.NET Core can be accessed through the following DNS name from within your cluster:

    drone-webapp-aspnet-core.default.svc.cluster.local (port 80)

To access ASP.NET Core from outside the cluster execute the following commands:

1. Get the ASP.NET Core URL and associate its hostname to your cluster external IP:

   export CLUSTER_IP=$(minikube ip) # On Minikube. Use: `kubectl cluster-info` on others K8s clusters
   echo "ASP.NET Core URL: http://aspnet-core.local"
   echo "$CLUSTER_IP  aspnet-core.local" | sudo tee -a /etc/hosts

2. Access ASP.NET Core using the obtained URL.
  1. 运行 helm history 命令,再次查看有关 drone-webapp 的历史记录信息
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ helm history drone-webapp
REVISION        UPDATED                         STATUS          CHART                   APP VERSION     DESCRIPTION
1               Thu Dec  9 14:59:26 2021        superseded      aspnet-core-1.3.18      0.0.1           Install complete
2               Thu Dec  9 15:08:18 2021        deployed        aspnet-core-1.3.18      0.0.2           Upgrade complete

回滚 Helm 发布

假设升级发布后,许多客户报告了关于网站的错误。 团队要求将发布回滚到应用的早期稳定版本。

  1. 使用 helm rollback 命令来回滚应用。
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ helm rollback drone-webapp 1
Rollback was a success! Happy Helming!
  1. 回滚完成后,使用 helm history 命令查看 Helm 部署历史记录
izhao_yiyi@Azure:~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src$ helm history drone-webapp
REVISION        UPDATED                         STATUS          CHART                   APP VERSION     DESCRIPTION
1               Thu Dec  9 14:59:26 2021        superseded      aspnet-core-1.3.18      0.0.1           Install complete
2               Thu Dec  9 15:08:18 2021        superseded      aspnet-core-1.3.18      0.0.2           Upgrade complete
3               Thu Dec  9 15:08:50 2021        deployed        aspnet-core-1.3.18      0.0.1           Rollback to 1

注意,列表中的最后一项显示以下信息:

  • 递增的修订号

  • 回滚发布的应用版本号

  • 回滚发布修订号的说明

实验环境删除

通过运行以下命令来删除所做的任何更改:

cd ~ && \
   rm -rf ~/clouddrive/mslearn-aks && \
   az group delete --name learn-helm-deploy-aks-rg --yes

本实验使用的所有命令

SubscriptionId=$(az account list --query '[0].id' -o tsv)
. <(wget -q -O - <https://raw.githubusercontent.com/MicrosoftDocs/mslearn-aks/main/infrastructure/setup/setup.sh> ) -s $SubscriptionId -n learn-helm-deploy-aks --use-acr false --install-dot-net false
helm repo add azure-marketplace https://marketplace.azurecr.io/helm/v1/repo
helm repo list
helm search repo aspnet
helm install aspnet-webapp azure-marketplace/aspnet-core
helm list
helm get manifest aspnet-webapp
kubectl get pods -o wide -w
helm delete aspnet-webapp
helm install --set replicaCount=5 aspnet-webapp azure-marketplace/aspnet-core
ls $HOME/.cache/helm/repository -l
cd ~/clouddrive/mslearn-aks/modules/learn-helm-deploy-aks/src
find drone-webapp-chart/ -print
vim drone-webapp-chart/Chart.yaml
helm dependency build ./drone-webapp-chart
find drone-webapp-chart/ -print
gzip -dc ./drone-webapp-chart/charts/common-1.10.3.tgz | tar -xf - -C ./drone-webapp-chart/charts/
find drone-webapp-chart/ -print
cat ~/clouddrive/mslearn-aks/create-aks-exports.txt
helm history drone-webapp
helm upgrade drone-webapp ./drone-webapp-chart
helm rollback drone-webapp 1
cd ~ && \
   rm -rf ~/clouddrive/mslearn-aks && \
   az group delete --name learn-helm-deploy-aks-rg --yes

你可能感兴趣的:(Kubernetes,azure,云计算,helm)