通过helm2构建kubernetes应用(二)

通过修改模板创建mysql应用

创建mysql模板

wangw@DESKTOP:~/app$ helm create mysql
Creating mysql

修改mysql/Chart.yaml

wangw@DESKTOP:~/app$ cat mysql/Chart.yaml
apiVersion: v1
appVersion: "5.7.12"
description: mysql for kubernetes
name: mysql
version: 0.1.0

修改mysql/templates/deployment.yaml

修改应用端口
ports:
  - name: http
    containerPort: 80
    protocol: TCP
#修改为
ports:
  - name: tcp-mysql
    containerPort: 3306
    protocol: TCP
添加环境变量
env:
- name: MYSQL_ROOT_PASSWORD
  value: {{ .Values.mysqlRootPassword }}
修改健康检查探针
livenessProbe:
  httpGet:
    path: /
    port: http
readinessProbe:
  httpGet:
    path: /
    port: http
#修改为
livenessProbe:
  exec:
      command:
      {{- if .Values.mysqlAllowEmptyPassword }}
      - mysqladmin
      - ping
      {{- else }}
      - sh
      - -c
      - "mysqladmin ping -u root -p${MYSQL_ROOT_PASSWORD}"
      {{- end }}
  initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
  periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
  timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }}
  successThreshold: {{ .Values.livenessProbe.successThreshold }}
  failureThreshold: {{ .Values.livenessProbe.failureThreshold }}
readinessProbe:
  exec:
      command:
      {{- if .Values.mysqlAllowEmptyPassword }}
      - mysqladmin
      - ping
      {{- else }}
      - sh
      - -c
      - "mysqladmin ping -u root -p${MYSQL_ROOT_PASSWORD}"
      {{- end }}
  initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
  periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
  timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }}
  successThreshold: {{ .Values.readinessProbe.successThreshold }}
  failureThreshold: {{ .Values.readinessProbe.failureThreshold }}
#其中{{ }}中指定的参数,其实是调用mysql/value.yaml中对应的值,所以后面还需要再values.yaml文件中添加相应的参数,支持if,if else判断
添加volume
volumes:
{{- if .Values.configurationFiles }}
# configmap作为配置文件
- name: configurations
  configMap:
    name: {{ template "mysql.fullname" . }}
{{- end }}
# pvc作为数据存储
- name: data
{{- if .Values.persistence.enabled }}
  persistentVolumeClaim:
    claimName: {{ .Values.persistence.existingClaim | default (include "mysql.fullname" .) }}
{{- else }}
  emptyDir: {}
{{- end -}}
# volume
挂载volume
volumeMounts:
# 挂载pv卷目录到mysql默认路径
- name: data
  mountPath: /var/lib/mysql
  {{- if .Values.persistence.subPath }}
  subPath: {{ .Values.persistence.subPath }}
  {{- end }}
{{- if .Values.configurationFiles }}
# 挂载configmap文件到mysql默认配置路径
- name: configurations
  mountPath: /etc/mysql/conf.d
{{- end }}
添加initContainers,处理mysql数据目录下块存储格式化后默认的lost+found文件夹,如果pv是文件类存储不存在此问题
initContainers:
- name: "remove-lost-found"
  image: "busybox:1.25.0"
  imagePullPolicy: {{ .Values.imagePullPolicy | quote }}
  command:  ["rm", "-fr", "/var/lib/mysql/lost+found"]
  volumeMounts:
  - name: data
    mountPath: /var/lib/mysql
    {{- if .Values.persistence.subPath }}
    subPath: {{ .Values.persistence.subPath }}
    {{- end }}
完整mysql/templates/deployment.yaml文件
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "mysql.fullname" . }}
  labels:
{{ include "mysql.labels" . | indent 4 }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "mysql.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "mysql.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
    spec:
    {{- with .Values.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
    {{- end }}
      # 加入初始化处理
      initContainers:
      - name: "remove-lost-found"
        image: "busybox:1.25.0"
        imagePullPolicy: {{ .Values.imagePullPolicy | quote }}
        command:  ["rm", "-fr", "/var/lib/mysql/lost+found"]
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          {{- if .Values.persistence.subPath }}
          subPath: {{ .Values.persistence.subPath }}
          {{- end }}
      containers:
      - name: {{ .Chart.Name }}
        image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
        imagePullPolicy: {{ .Values.image.pullPolicy }}
        env:
        - name: MYSQL_ROOT_PASSWORD
          value: {{ .Values.mysqlRootPassword }}
        ports:
        - name: tcp-mysql
          containerPort: 3306
          protocol: TCP
        livenessProbe:
          exec:
            command:
            {{- if .Values.mysqlAllowEmptyPassword }}
            - mysqladmin
            - ping
            {{- else }}
            - sh
            - -c
            - "mysqladmin ping -u root -p${MYSQL_ROOT_PASSWORD}"
            {{- end }}
          initialDelaySeconds: {{ .Values.livenessProbe.initialDelaySeconds }}
          periodSeconds: {{ .Values.livenessProbe.periodSeconds }}
          timeoutSeconds: {{ .Values.livenessProbe.timeoutSeconds }}
          successThreshold: {{ .Values.livenessProbe.successThreshold }}
          failureThreshold: {{ .Values.livenessProbe.failureThreshold }}
        readinessProbe:
          exec:
            command:
            {{- if .Values.mysqlAllowEmptyPassword }}
            - mysqladmin
            - ping
            {{- else }}
            - sh
            - -c
            - "mysqladmin ping -u root -p${MYSQL_ROOT_PASSWORD}"
            {{- end }}
          initialDelaySeconds: {{ .Values.readinessProbe.initialDelaySeconds }}
          periodSeconds: {{ .Values.readinessProbe.periodSeconds }}
          timeoutSeconds: {{ .Values.readinessProbe.timeoutSeconds }}
          successThreshold: {{ .Values.readinessProbe.successThreshold }}
          failureThreshold: {{ .Values.readinessProbe.failureThreshold }}
        resources:
          {{- toYaml .Values.resources | nindent 12 }}
        volumeMounts:
        # 挂载pv卷目录到mysql默认路径
        - name: data
          mountPath: /var/lib/mysql
          {{- if .Values.persistence.subPath }}
          subPath: {{ .Values.persistence.subPath }}
          {{- end }}
        {{- if .Values.configurationFiles }}
        # 挂载configmap文件到mysql默认配置路径
        - name: configurations
          mountPath: /etc/mysql/conf.d
        {{- end }}
      volumes:
      {{- if .Values.configurationFiles }}
      # configmap作为配置文件
      - name: configurations
        configMap:
          name: {{ template "mysql.fullname" . }}
      {{- end }}
      # pvc作为数据存储
      - name: data
      {{- if .Values.persistence.enabled }}
        persistentVolumeClaim:
          claimName: {{ .Values.persistence.existingClaim | default (include "mysql.fullname" .) }}
      {{- else }}
        emptyDir: {}
      {{- end -}}
    {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
    {{- with .Values.affinity }}
      affinity:
        {{- toYaml . | nindent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
    {{- end }}

添加mysql/templates/pvc.yaml,定义pvc

{{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) }}
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: {{ template "mysql.fullname" . }}
  labels:
    app: {{ template "mysql.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
spec:
  accessModes:
    - {{ .Values.persistence.accessMode | quote }}
  resources:
    requests:
      storage: {{ .Values.persistence.size | quote }}
{{- if .Values.persistence.storageClass }}
{{- if (eq "-" .Values.persistence.storageClass) }}
  storageClassName: ""
{{- else }}
  storageClassName: "{{ .Values.persistence.storageClass }}"
{{- end }}
{{- end }}
{{- end }}
# {{ }}中引用的值需要在values.yaml中添加定义

添加mysql/templates/configmap.yaml,定义configmap

{{- if .Values.configurationFiles }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "mysql.fullname" . }}
data:
{{- range $key, $val := .Values.configurationFiles }}
  {{ $key }}: |-
{{ $val | indent 4}}
{{- end }}
{{- end -}}
# {{ }}中引用的值需要在values.yaml中添加定义

修改mysql/values.yaml

# 修改容器镜像
image:
  repository: mysql
  tag: 5.7.12
# 修改服务端口
service:
  type: ClusterIP
  port: 3306
# 修改资源配额
resources:
  limits:
    cpu: 500m
    memory: 1Gi
  requests:
    cpu: 100m
    memory: 256Mi
# 添加root密码配置
mysqlRootPassword: admin
# 添加健康探针配置
livenessProbe:
  initialDelaySeconds: 30
  periodSeconds: 10
  timeoutSeconds: 5
  successThreshold: 1
  failureThreshold: 3

readinessProbe:
  initialDelaySeconds: 5
  periodSeconds: 10
  timeoutSeconds: 1
  successThreshold: 1
  failureThreshold: 3
# 添加存储卷相关配置
persistence:
  enabled: true
  storageClass: "longhorn"
  accessMode: ReadWriteOnce
  size: 8Gi
# 添加configmap引用配置文件

configurationFiles:
  mysql.cnf: |-
    [mysqld]
    skip-name-resolve

检查配置是否正确,保证没有错误,如果有错误,按照提示的文件和行修改

wangw@DESKTOP:~/app$ helm lint mysql/
==> Linting mysql/
[INFO] Chart.yaml: icon is recommended

1 chart(s) linted, no failures

打包测试

wangw@DESKTOP:~/app$ helm package mysql/
Successfully packaged chart and saved it to: /home/wangw/app/mysql-0.1.0.tgz
wangw@DESKTOP:~/app$ helm repo update
Hang tight while we grab the latest from your chart repositories...
...Successfully got an update from the "localrepo" chart repository
...Successfully got an update from the "stable" chart repository
Update Complete.
wangw@DESKTOP:~/app$ helm search mysql
NAME                                    CHART VERSION   APP VERSION     DESCRIPTION
localrepo/mysql                         0.1.0           5.7.12          mysql for kubernetes
stable/mysql                            1.4.0           5.7.27          Fast, reliable, scalable
# localrepo/mysql即为我们打包的应用,可以看到包版本、应用版本和应用描述是我们所设置的值

部署测试

wangw@DESKTOP:~/app$ helm install localrepo/mysql --name mysql --namespace default
NAME:   mysql
LAST DEPLOYED: Wed Oct 23 18:32:41 2019
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/ConfigMap
NAME   DATA  AGE
mysql  1     0s

==> v1/Deployment
NAME   READY  UP-TO-DATE  AVAILABLE  AGE
mysql  0/1    0           0          0s

==> v1/PersistentVolumeClaim
NAME   STATUS   VOLUME    CAPACITY  ACCESS MODES  STORAGECLASS  AGE
mysql  Pending  longhorn  0s

==> v1/Pod(related)
NAME                    READY  STATUS   RESTARTS  AGE
mysql-66957cc666-ts7gt  0/1    Pending  0         0s

==> v1/Service
NAME   TYPE       CLUSTER-IP    EXTERNAL-IP  PORT(S)   AGE
mysql  ClusterIP  10.43.122.51  <none>       3306/TCP  0s
# 稍等一会后,查看应用状态
wangw@DESKTOP:~/app$ helm status mysql
LAST DEPLOYED: Wed Oct 23 18:32:41 2019
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/ConfigMap
NAME   DATA  AGE
mysql  1     71s

==> v1/Deployment
NAME   READY  UP-TO-DATE  AVAILABLE  AGE
mysql  1/1    1           1          71s

==> v1/PersistentVolumeClaim
NAME   STATUS  VOLUME                                    CAPACITY  ACCESS MODES  STORAGECLASS  AGE
mysql  Bound   pvc-a5fe441e-9bad-4ab2-9627-cf957d02b491  8Gi       RWO           longhorn      71s

==> v1/Pod(related)
NAME                    READY  STATUS   RESTARTS  AGE
mysql-66957cc666-ts7gt  1/1    Running  0         71s

==> v1/Service
NAME   TYPE       CLUSTER-IP    EXTERNAL-IP  PORT(S)   AGE
mysql  ClusterIP  10.43.122.51  <none>       3306/TCP  71s

测试连接

# 本地代理
wangw@DESKTOP:~$ kubectl port-forward mysql-66957cc666-ts7gt 3306:3306
Forwarding from 127.0.0.1:3306 -> 3306
Forwarding from [::1]:3306 -> 3306
# 安装mysql-client
wangw@DESKTOP:~$ sudo apt install mysql-client
# 连接测试
wangw@DESKTOP:~$ mysql -h 127.0.0.1 -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 10637
Server version: 5.7.12 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
mysql> mysql> show status\g;
+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Variable_name                                 | Value                                                                                                                                                                                                                                       |
+-----------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Aborted_clients                               | 0                                                                                                                                                                                                                                           |
| Aborted_connects                              | 0                                                                                                                                                                                                                                           |
| Binlog_cache_disk_use                         | 0                                                                                                                                                                                                                                           |
| Binlog_cache_use                              | 0                                                                                                                                                                                                                                           |
| Binlog_stmt_cache_disk_use                    | 0                                                                                                                                                                                                                                           |
| Binlog_stmt_cache_use                         | 0                                                                                                                                                                                                                                           |
| Bytes_received                                | 306                                                                                                                                                                                                                                         |
| Bytes_sent                                    | 20525                                           

下一篇:多应用打包交付

posted @ 2020-10-19 19:18  longtds  阅读(136)  评论(0编辑  收藏  举报