Helm 概述与安装
1 ) 概述
- k8s中官方包管理工具, 官网: https://helm.sh/
- 用 Yaml 管理多个应用同时部署 - 不需要在不同的yaml中写两遍,执行两遍
- 解决一键部署的问题,联合部署
 
- 实现了部署的版本管理 - 可以实现版本回滚
 
- 应用和配置分离
2 )安装
- $ wget https://get.helm.sh/helm-v3.4.1-linux-amd64.tar.gz -O helm-v3.4.1-linux-amd64.tar.gz下载
- $ tar -zxvf helm-v3.4.1-linux-amd64.tar.gz解压
- $ sudo mv linux-amd64/helm /usr/local/bin/helm移动到bin目录
- $ which helm验证命令
- $ helm ls列出
部署 Helm Chart
-  $ helm create nginxCreating nginx- 这样会在当前创建一个 nginx 的目录
- 在这个目录里创建了一个个的文件
 
-  $ cd nginx && ls -lahtotal 16K drwxr-xr-x 4 parallels parallels 93 Apr 28 18:53 . drwx------. 20 parallels parallels 4.0K Apr 28 18:53 .. drwxr-xr-x 2 parallels parallels 6 Apr 28 18:53 charts -rw-r--r-- 1 parallels parallels 1.1K Apr 28 18:53 Chart.yaml -rw-r--r-- 1 parallels parallels 349 Apr 28 18:53 .helmignore drwxr-xr-x 3 parallels parallels 162 Apr 28 18:53 templates -rw-r--r-- 1 parallels parallels 1.8K Apr 28 18:53 values.yaml
-  $ cat Chart.yamlapiVersion: v2 name: nginx description: A Helm chart for Kubernetes# A chart can be either an 'application' or a 'library' chart. # # Application charts are a collection of templates that can be packaged into versioned archives # to be deployed. # # Library charts provide useful utilities or functions for the chart developer. They're included as # a dependency of application charts to inject those utilities and functions into the rendering # pipeline. Library charts do not define any templates and therefore cannot be deployed. type: application# This is the chart version. This version number should be incremented each time you make changes # to the chart and its templates, including the app version. # Versions are expected to follow Semantic Versioning (https://semver.org/) version: 0.1.0# This is the version number of the application being deployed. This version number should be # incremented each time you make changes to the application. Versions are not expected to # follow Semantic Versioning. They should reflect the version the application is using. appVersion: 1.16.0- 看下这里的关键信息
 
-  charts 目录是你所有的依赖库都在这个地方 
-  templates 目录是模板目录,为了更快更好的写Services 
-  $ cd templates && cat service.yamlapiVersion: v1 kind: Service metadata:name: {{ include "nginx.fullname" . }}labels:{{- include "nginx.labels" . | nindent 4 }} spec:type: {{ .Values.service.type }}ports:- port: {{ .Values.service.port }}targetPort: httpprotocol: TCPname: httpselector:{{- include "nginx.selectorLabels" . | nindent 4 }}- 看这里用的是 {{ }}来引用的变量
- 这是 helm 模板的特色,原生的 yaml 文件不支持
- helm 把一些变量抽取出来,把其定义成可替换的字段,让其可复用
- 这里 {{ .Values.service.type }}很重要, 这里的 Values 是从上层 values.yaml 中读取
 
- 看这里用的是 
-  上述 values.yaml 中的变量可实现彻底的应用分离 - $ cp values.yaml values-test.yaml
- 这样拷贝出一份test环境的,之后进行修改
- 在部署 helm charts 时可指定特定的 values 文件
- 这是做配置和应用分离的方法
 
- $ 
-  现在可以对其进行打包了,在 nginx 上层目录中 - $ helm package nginx这时候会在nginx同级打一个 tgz 包
- $ helm install nginx nginx-0.1.0.tgz安装- 它底层会调 kubectl部署相关的命令
 
- 它底层会调 
- $ helm ls列出刚刚部署的 nginx- 可以根据这里的 REVISION 进行升级回滚
 
 
- $ 
-  如果要删除 $ helm delete nginx这样相关部署都会被删除
在 JCR 中创建 Helm 仓库
- 私有 Helm 仓库需要有 - Helm-local 开发仓库
- Helm-test-local 测试仓库
- Helm-prod-local 生产仓库
- helm-remote 远程仓库
- 以及 Helm 虚拟仓库
 
- 创建方法,如同docker仓库,类型选择 Helm
- 注意在虚拟 helm 仓库中,把新增的仓库加上
- 在 JCR 系统的 JFrog Container Registry/Artifacts 中 - 选择 helm 仓库,点击右上角 Set Me Up
- 会自动生成 helm 的 repo 添加的命令
- $ helm repo add helm http://10.211.10.2:8081/artifactory/helm --username admin --password AP47Gv1YwDSQWJQau87twsytQRB
- 这时候会用这里的用户名和密码,连接到 server
- 这样,以后上传就自动鉴权了
- 紧接着在下面的一条命令就是部署命令,这里先不做赘述
 
创建应用的 Helm chart
1 ) 概述
- Helm Chart 是官方子项目,我们用 Helm Chart 部署应用
- 在我们的应用项目中部署,这个简单的博客应用包含 - 博客应用本身
- 博客应用数据库
- ingress 负载均衡网络
 
- 这样来看,至少需要部署三个服务
- 每次部署如果都执行多个yaml文件
- 这样,很难做到版本的同进同退
- 基于这样的考虑,为博客应用创建 Helm chart
- 目的是一键部署,一键回退
2 )创建
- 可以创建这个应用的helm目录, 目录结构如下
k8s-blog
├── values-dev.yaml            # 开发环境变量
├── values-test.yaml            # 测试环境变量
├── values-prod.yaml          # 生产环境变量
├── Chart.yaml                  
├── charts/                           # 放一些第三方不变的依赖 默认是空的
└── templates/
│       ├── deployment.yaml
│       ├── mysql.yaml
│       ├── service.yaml
│       ├── _helpers.tpl
│       ├── ingress.yaml
│       └── NOTES.txt
3 )Chart.yaml 重要
apiVersion: v1
appVersion: "1.0"
description: A Helm chart for K8s
name: k8s-blog
version: 0.1.1
这里面定义的是 .Release 的变量,不再 values-x.yaml 文件中的
4 )development.yaml
示例
apiVersion: apps/v1
kind: Deployment
metadata:name: {{ .Release.Name }}
spec:replicas: 3selector:matchLabels:app: {{ .Release.Name }}template:metadata:labels:app: {{ .Release.Name }}spec:containers:- name: {{ .Release.Name }}image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"ports:- containerPort: {{ .Values.service.port }}env:- name: MYSQL_PORTvalue: "30306"- name: MYSQL_SERVERvalue: "node1.k8s"- name: MYSQL_DB_NAMEvalue: "{{ .Values.mysql.dbName }}"- name: MYSQL_USER_TESTvalue: "root"- name: MYSQL_PASSWORD_TESTvalueFrom:secretKeyRef:name: mysql-password-testkey: MYSQL_PASSWORD_TESTimagePullSecrets:- name: regcred-local
5 )service.yaml
apiVersion: v1
kind: Service
metadata:name: {{ .Release.Name }}labels:app: {{ .Release.Name }}
spec:ports:- name: port2protocol: TCPport: {{ .Values.service.port }}nodePort: {{ .Values.service.nodePort }}selector:app: {{ .Release.Name }}type: NodePort
6 ) mysql.yaml
示例
apiVersion: v1
kind: Service
metadata:name: mysql57labels:app: mysql
spec:ports:- port: 3306name: mysqlnodePort: {{ .Values.mysql.port }}type: NodePortselector:app: mysql
---
apiVersion: apps/v1
kind: StatefulSet
metadata:name: mysql
spec:selector:matchLabels:app: mysql # has to match .spec.template.metadata.labelsserviceName: "mysql"replicas: 1 # by default is 1template:metadata:labels:app: mysql # has to match .spec.selector.matchLabelsspec:terminationGracePeriodSeconds: 10containers:- name: mysqlimage: mysql:8.0ports:- containerPort: 3306name: mysqlvolumeMounts:- name: host-pathmountPath: /var/lib/mysqlenv:- name: MYSQL_ROOT_PASSWORDvalue: "password"volumes:- name: host-pathhostPath:path: /tmp/mysqltype: DirectoryOrCreate
7 ) values-dev.yaml
默认模板示例
# Default values for nginx.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.replicaCount: 1image:registry: 10.211.10.2:8081repository: 10.211.10.2:8081/docker/k8sblogpullPolicy: IfNotPresent# Overrides the image tag whose default is the chart appVersion.tag: "1.1"imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""mysql:port: 30306dbName: blogDBserviceAccount:# Specifies whether a service account should be createdcreate: true# Annotations to add to the service accountannotations: {}# The name of the service account to use.# If not set and create is true, a name is generated using the fullname templatename: ""podAnnotations: {}podSecurityContext: {}# fsGroup: 2000securityContext: {}# capabilities:#   drop:#   - ALL# readOnlyRootFilesystem: true# runAsNonRoot: true# runAsUser: 1000service:type: ClusterIPport: 80ingress:enabled: falseannotations: {}# kubernetes.io/ingress.class: nginx# kubernetes.io/tls-acme: "true"hosts:- host: chart-example.localpaths: []tls: []#  - secretName: chart-example-tls#    hosts:#      - chart-example.localresources: {}# We usually recommend not to specify default resources and to leave this as a conscious# choice for the user. This also increases chances charts run on environments with little# resources, such as Minikube. If you do want to specify resources, uncomment the following# lines, adjust them as necessary, and remove the curly braces after 'resources:'.# limits:#   cpu: 100m#   memory: 128Mi# requests:#   cpu: 100m#   memory: 128Miautoscaling:enabled: falseminReplicas: 1maxReplicas: 100targetCPUUtilizationPercentage: 80# targetMemoryUtilizationPercentage: 80nodeSelector: {}tolerations: []affinity: {}
上面定义的变量,可在此文件中,按照其要求的格式,进行补充
8 ) ingress
默认 ingress 的模板
{{- if .Values.ingress.enabled -}}
{{- $fullName := include "nginx.fullname" . -}}
{{- $svcPort := .Values.service.port -}}
{{- if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:name: {{ $fullName }}labels:{{- include "nginx.labels" . | nindent 4 }}{{- with .Values.ingress.annotations }}annotations:{{- toYaml . | nindent 4 }}{{- end }}
spec:{{- if .Values.ingress.tls }}tls:{{- range .Values.ingress.tls }}- hosts:{{- range .hosts }}- {{ . | quote }}{{- end }}secretName: {{ .secretName }}{{- end }}{{- end }}rules:{{- range .Values.ingress.hosts }}- host: {{ .host | quote }}http:paths:{{- range .paths }}- path: {{ . }}backend:serviceName: {{ $fullName }}servicePort: {{ $svcPort }}{{- end }}{{- end }}{{- end }}
- 这个可以在项目中,先不配置,以上是默认ingress模板
9 ) 对项目进行打包,示例
-  $ helm package k8sblog ./k8sblog,这样打成了 tgz 包
-  $ helm install k8sblog ./k8sblog-0.1.1.tgz安装
-  必要的状态检查 - kubeclt get po
- kubeclt get svc -o wide
- kubectl logs xxx
- …
 
-  部署完成,基于服务的ip地址和端口进行访问,比如 - http://10.211.10.5:30002
- 这里 10.211.10.5 是 node1 的地址
- 从上面 kubectl get svc -o wide命令中可见
 
-  通过这种方式,一键部署,当有10个微服务也可以这么写,非常强大 
10 )私有镜像中心JCR同步Helm Chart 应用
- 通过本地文件方式安装不方便,而且容易误操作
- 我们选择用 helm 仓库来管理,就像管理发布包一样
- 在JCR镜像中心获取 helm 添加仓库的命令,如 - $ helm repo add helm http://10.211.10.2:8081/artifactory/helm --username admin --password AP47Gv1YwDSQWJQau87twsytQRB
 
- $ 
- 添加完仓库后,使用 $ helm repo ls可查看已经添加的仓库
- $ helm repo update从远端获取仓库
- 如果需要部署,则执行 - $ curl -uadmin:AP47Gv1YwDSQWJQau87twsytQRB -T <PATH_TO_FILE> "http://10.211.10.2:8081/artifactory/helm/<TARGET_FILE_PATH>"
- 基于上述规则,修改为
- $ curl -uadmin:AP47Gv1YwDSQWJQau87twsytQRB -T k8sblog-0.1.1.tgz "http://10.211.10.2:8081/artifactory/helm/k8sblog-0.1.1.tgz
- 默认会上传到 helm-local 仓库
 
- $ 
- 上传完了,再次更新 $ helm repo update
- $ helm search repo k8sblog可以搜索到
- 从远程JCR部署,替换本地安装的方式 - $ helm install k8sblog helm/k8sblog安装部署
 
- $ 
- 注意,在JCR的helm-local仓库中会有一个 index.yaml 的索引文件 - 可以看到为仓库下的目录文件建立索引,每次更新,该文件也会被更新
 
- 这样,在服务器上不用打本地包,通过仓库来管理和部署
Helm 版本的升级和回滚
1 )升级
- 在项目 Chart.yaml 中,将版本号升级
- 远程仓库更新打包后进行部署,参考上述手动打包和上传部署 - $ git pull
- $ helm package k8sblog打包成新tgz包
- $ curl -uadmin ...注意文件的版本
 
- $ 
- $ helm upgrade k8sblog helm/k8sblog --version 0.1.2升级某个版本
- $ kubectl get po升级后的必要检查,此处省略其他检查命令
2 )回退
- $ helm rollback k8sblog 1回退到上一个版本
在不同环境下部署 Helm Chart
- 在项目的 yaml 文件中,包含多个 value-xxx.yaml 文件
- 创建测试和生产环境命名空间 - $ kubectl create ns test
- $ kubectl create ns prod
 
- $ 
- 检查所有命名空间 - $ kubectl get ns
 
- $ 
- 将打包好的 tgz 部署到测试命名空间 - $ helm install k8sblog k8sblog-0.1.1.tgz -f k8sblog/values-test.yaml -n test- 这里通过 -f 指定文件,-n指定命名空间
 
- $ kubectl get po -n test检查
- $ kubectl get svc -n test检查
 
- $ 
- 如果需要删除,则 $ helm delete k8sblog -n test
- 这样实现了数据的隔离性,prod的也同样进行部署