返回总目录页

kubernetes之包管理器Helm

安装helm

安装helm客户端

[machangwei@mcwk8s-master ~]$ curl https://raw.githubusercontent.com/kubernetes/helm/master/scripts/get | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:--  0:00:24 --:--:--     0
curl: (35) TCP connection reset by peer
[machangwei@mcwk8s-master ~]$ vim azHelm.sh
#!/usr/bin/env bash

# Copyright The Helm Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# The install script is based off of the MIT-licensed script from glide,
# the package manager for Go: https://github.com/Masterminds/glide.sh/blob/master/get

PROJECT_NAME="helm"
TILLER_NAME="tiller"

: ${USE_SUDO:="true"}
: ${HELM_INSTALL_DIR:="/usr/local/bin"}

# initArch discovers the architecture for this system.
initArch() {
  ARCH=$(uname -m)
  case $ARCH in
    armv5*) ARCH="armv5";;
    armv6*) ARCH="armv6";;
    armv7*) ARCH="arm";;
    aarch64) ARCH="arm64";;
    x86) ARCH="386";;
    x86_64) ARCH="amd64";;
    i686) ARCH="386";;
    i386) ARCH="386";;
  esac
}

# initOS discovers the operating system for this system.
initOS() {
  OS=$(echo `uname`|tr '[:upper:]' '[:lower:]')

  case "$OS" in
    # Minimalist GNU for Windows
    mingw*) OS='windows';;
  esac
}

# runs the given command as root (detects if we are root already)
runAsRoot() {
  if [ $EUID -ne 0 -a "$USE_SUDO" = "true" ]; then
    sudo "${@}"
  else
    "${@}"
  fi
}

# verifySupported checks that the os/arch combination is supported for
# binary builds.
verifySupported() {
  local supported="darwin-amd64\nlinux-386\nlinux-amd64\nlinux-arm\nlinux-arm64\nlinux-ppc64le\nlinux-s390x\nwindows-amd64"
  if ! echo "${supported}" | grep -q "${OS}-${ARCH}"; then
    echo "No prebuilt binary for ${OS}-${ARCH}."
    echo "To build from source, go to https://github.com/helm/helm"
    exit 1
  fi

  if ! type "curl" > /dev/null && ! type "wget" > /dev/null; then
    echo "Either curl or wget is required"
    exit 1
  fi
}

# checkDesiredVersion checks if the desired version is available.
checkDesiredVersion() {
  if [ "x$DESIRED_VERSION" == "x" ]; then
    # Pinning tag to v2.17.0 as per https://github.com/helm/helm/issues/9607
    TAG=v2.17.0
  else
    TAG=$DESIRED_VERSION
  fi
}

# checkHelmInstalledVersion checks which version of helm is installed and
# if it needs to be changed.
checkHelmInstalledVersion() {
  if [[ -f "${HELM_INSTALL_DIR}/${PROJECT_NAME}" ]]; then
    local version=$("${HELM_INSTALL_DIR}/${PROJECT_NAME}" version -c | grep '^Client' | cut -d'"' -f2)
    if [[ "$version" == "$TAG" ]]; then
      echo "Helm ${version} is already ${DESIRED_VERSION:-latest}"
      return 0
    else
      echo "Helm ${TAG} is available. Changing from version ${version}."
      return 1
    fi
  else
    return 1
  fi
}

# downloadFile downloads the latest binary package and also the checksum
# for that binary.
downloadFile() {
  HELM_DIST="helm-$TAG-$OS-$ARCH.tar.gz"
  DOWNLOAD_URL="https://get.helm.sh/$HELM_DIST"
  CHECKSUM_URL="$DOWNLOAD_URL.sha256"
  HELM_TMP_ROOT="$(mktemp -dt helm-installer-XXXXXX)"
  HELM_TMP_FILE="$HELM_TMP_ROOT/$HELM_DIST"
  HELM_SUM_FILE="$HELM_TMP_ROOT/$HELM_DIST.sha256"
  echo "Downloading $DOWNLOAD_URL"
  if type "curl" > /dev/null; then
    curl -SsL "$CHECKSUM_URL" -o "$HELM_SUM_FILE"
  elif type "wget" > /dev/null; then
    wget -q -O "$HELM_SUM_FILE" "$CHECKSUM_URL"
  fi
  if type "curl" > /dev/null; then
    curl -SsL "$DOWNLOAD_URL" -o "$HELM_TMP_FILE"
  elif type "wget" > /dev/null; then
    wget -q -O "$HELM_TMP_FILE" "$DOWNLOAD_URL"
  fi
}

# installFile verifies the SHA256 for the file, then unpacks and
# installs it.
installFile() {
  HELM_TMP="$HELM_TMP_ROOT/$PROJECT_NAME"
  local sum=$(openssl sha1 -sha256 ${HELM_TMP_FILE} | awk '{print $2}')
  local expected_sum=$(cat ${HELM_SUM_FILE})
  if [ "$sum" != "$expected_sum" ]; then
    echo "SHA sum of ${HELM_TMP_FILE} does not match. Aborting."
    exit 1
  fi

  mkdir -p "$HELM_TMP"
  tar xf "$HELM_TMP_FILE" -C "$HELM_TMP"
  HELM_TMP_BIN="$HELM_TMP/$OS-$ARCH/$PROJECT_NAME"
  TILLER_TMP_BIN="$HELM_TMP/$OS-$ARCH/$TILLER_NAME"
  echo "Preparing to install $PROJECT_NAME and $TILLER_NAME into ${HELM_INSTALL_DIR}"
  runAsRoot cp "$HELM_TMP_BIN" "$HELM_INSTALL_DIR/$PROJECT_NAME"
  echo "$PROJECT_NAME installed into $HELM_INSTALL_DIR/$PROJECT_NAME"
  if [ -x "$TILLER_TMP_BIN" ]; then
    runAsRoot cp "$TILLER_TMP_BIN" "$HELM_INSTALL_DIR/$TILLER_NAME"
    echo "$TILLER_NAME installed into $HELM_INSTALL_DIR/$TILLER_NAME"
  else
    echo "info: $TILLER_NAME binary was not found in this release; skipping $TILLER_NAME installation"
  fi
}

# fail_trap is executed if an error occurs.
fail_trap() {
  result=$?
  if [ "$result" != "0" ]; then
    if [[ -n "$INPUT_ARGUMENTS" ]]; then
      echo "Failed to install $PROJECT_NAME with the arguments provided: $INPUT_ARGUMENTS"
      help
    else
      echo "Failed to install $PROJECT_NAME"
    fi
    echo -e "\tFor support, go to https://github.com/helm/helm."
  fi
  cleanup
  exit $result
}

# testVersion tests the installed client to make sure it is working.
testVersion() {
  set +e
  HELM="$(command -v $PROJECT_NAME)"
  if [ "$?" = "1" ]; then
    echo "$PROJECT_NAME not found. Is $HELM_INSTALL_DIR on your "'$PATH?'
    exit 1
  fi
  set -e
  echo "Run '$PROJECT_NAME init' to configure $PROJECT_NAME."
}

# help provides possible cli installation arguments
help () {
  echo "Accepted cli arguments are:"
  echo -e "\t[--help|-h ] ->> prints this help"
  echo -e "\t[--version|-v <desired_version>]"
  echo -e "\te.g. --version v2.4.0  or -v latest"
  echo -e "\t[--no-sudo]  ->> install without sudo"
}

# cleanup temporary files to avoid https://github.com/helm/helm/issues/2977
cleanup() {
  if [[ -d "${HELM_TMP_ROOT:-}" ]]; then
    rm -rf "$HELM_TMP_ROOT"
  fi
}

# Execution

#Stop execution on any error
trap "fail_trap" EXIT
set -e

# Parsing input arguments (if any)
export INPUT_ARGUMENTS="${@}"
set -u
while [[ $# -gt 0 ]]; do
  case $1 in
    '--version'|-v)
       shift
       if [[ $# -ne 0 ]]; then
           export DESIRED_VERSION="${1}"
       else
           echo -e "Please provide the desired version. e.g. --version v2.4.0 or -v latest"
           exit 0
       fi
       ;;
    '--no-sudo')
       USE_SUDO="false"
       ;;
    '--help'|-h)
       help
       exit 0
       ;;
    *) exit 1
       ;;
  esac
  shift
done
set +u

initArch
initOS
verifySupported
checkDesiredVersion
if ! checkHelmInstalledVersion; then
  downloadFile
  installFile
fi
testVersion
cleanup
azHelm.sh
[machangwei@mcwk8s-master ~]$ ls azHelm.sh  #无法curl下载下来,那么浏览器访问,直接复制过来执行
azHelm.sh
[machangwei@mcwk8s-master ~]$ sh azHelm.sh 
Downloading https://get.helm.sh/helm-v2.17.0-linux-amd64.tar.gz
Preparing to install helm and tiller into /usr/local/bin
helm installed into /usr/local/bin/helm
tiller installed into /usr/local/bin/tiller
Run 'helm init' to configure helm.
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ helm version #还没有安装tiller
Client: &version.Version{SemVer:"v2.17.0", GitCommit:"a690bad98af45b015bd3da1a41f6218b1a451dbe", GitTreeState:"clean"}
Error: could not find tiller

Tiller服务器

[machangwei@mcwk8s-master ~]$ helm init #安装tiller
Creating /home/machangwei/.helm 
Creating /home/machangwei/.helm/repository 
Creating /home/machangwei/.helm/repository/cache 
Creating /home/machangwei/.helm/repository/local 
Creating /home/machangwei/.helm/plugins 
Creating /home/machangwei/.helm/starters 
Creating /home/machangwei/.helm/cache/archive 
Creating /home/machangwei/.helm/repository/repositories.yaml 
Adding stable repo with URL: https://charts.helm.sh/stable 
Adding local repo with URL: http://127.0.0.1:8879/charts 
$HELM_HOME has been configured at /home/machangwei/.helm.

Tiller (the Helm server-side component) has been installed into your Kubernetes Cluster.

Please note: by default, Tiller is deployed with an insecure 'allow unauthenticated users' policy.
To prevent this, run `helm init` with the --tiller-tls-verify flag.
For more information on securing your installation see: https://v2.helm.sh/docs/securing_installation/


下面查看tiller的service,deployment和pod信息
[machangwei@mcwk8s-master ~]$ kubectl get --namespace=kubesystem pod
No resources found in kubesystem namespace.
[machangwei@mcwk8s-master ~]$ kubectl get --namespace=kube-system svc tiller-deploy
NAME            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)     AGE
tiller-deploy   ClusterIP   10.106.156.251   <none>        44134/TCP   3m8s
[machangwei@mcwk8s-master ~]$ kubectl get sevice
error: the server doesn't have a resource type "sevice"
[machangwei@mcwk8s-master ~]$ kubectl get service
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   31d
[machangwei@mcwk8s-master ~]$ kubectl get --namespace=kube-system svc tiller-deploy
NAME            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)     AGE
tiller-deploy   ClusterIP   10.106.156.251   <none>        44134/TCP   3m38s
[machangwei@mcwk8s-master ~]$ kubectl get deployment
No resources found in default namespace.
[machangwei@mcwk8s-master ~]$ kubectl get --namespace=kube-system  deployment tiller-deploy
NAME            READY   UP-TO-DATE   AVAILABLE   AGE
tiller-deploy   1/1     1            1           4m59s
[machangwei@mcwk8s-master ~]$ kubectl get pod
No resources found in default namespace.
[machangwei@mcwk8s-master ~]$ kubectl get --namespace=kube-system pod tiller-deploy-7d5bf6499f-lmvps
NAME                             READY   STATUS    RESTARTS   AGE
tiller-deploy-7d5bf6499f-lmvps   1/1     Running   0          5m50s


下面添加helm命令补全的操作
[machangwei@mcwk8s-master ~]$ helm completion bash > .helmrc  
[machangwei@mcwk8s-master ~]$ echo "source .helmrc" >> .bashrc 
[machangwei@mcwk8s-master ~]$ source .bashrc 
[machangwei@mcwk8s-master ~]$ helm 
completion  delete      fetch       history     init        install     list        plugin      reset       search      status      test        verify      
create      dependency  get         home        inspect     lint        package     repo        rollback    serve       template    upgrade     version     
[machangwei@mcwk8s-master ~]$ helm install --
--atomic                      --home=                       --name=                       --replace                     --tiller-namespace=           --tls-verify
--ca-file                     --host                        --namespace                   --repo                        --timeout                     --username
--ca-file=                    --host=                       --namespace=                  --repo=                       --timeout=                    --username=
--cert-file                   --key-file                    --name-template               --set                         --tls                         --values
--cert-file=                  --key-file=                   --name-template=              --set=                        --tls-ca-cert                 --values=
--debug                       --keyring                     --no-crd-hook                 --set-file                    --tls-ca-cert=                --verify
--dep-up                      --keyring=                    --no-hooks                    --set-file=                   --tls-cert                    --version
--description                 --kubeconfig                  --output                      --set-string                  --tls-cert=                   --version=
--description=                --kubeconfig=                 --output=                     --set-string=                 --tls-hostname                --wait
--devel                       --kube-context                --password                    --tiller-connection-timeout   --tls-hostname=               
--dry-run                     --kube-context=               --password=                   --tiller-connection-timeout=  --tls-key                     
--home                        --name                        --render-subchart-notes       --tiller-namespace            --tls-key=                    
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ helm  version  #x现在可以看版本了
Client: &version.Version{SemVer:"v2.17.0", GitCommit:"a690bad98af45b015bd3da1a41f6218b1a451dbe", GitTreeState:"clean"}
Server: &version.Version{SemVer:"v2.17.0", GitCommit:"a690bad98af45b015bd3da1a41f6218b1a451dbe", GitTreeState:"clean"}
[machangwei@mcwk8s-master ~]$ 

 

使用helm(安装MySQL栗子,添加权限)

stable 官方仓库;local 本地仓库

[machangwei@mcwk8s-master ~]$ helm search  #可安装chart
NAME                                     CHART VERSION    APP VERSION                DESCRIPTION                                                 
stable/acs-engine-autoscaler             2.2.2            2.1.1                      DEPRECATED Scales worker nodes within agent pools           
stable/aerospike                         0.3.5            v4.5.0.5                   DEPRECATED A Helm chart for Aerospike in Kubernetes         
stable/airflow                           7.13.3           1.10.12                    DEPRECATED - please use: https://github.com/airflow-helm/...
stable/ambassador                        5.3.2            0.86.1                     DEPRECATED A Helm chart for Datawire Ambassador             
stable/anchore-engine                    1.7.0            0.7.3                      Anchore container analysis and policy evaluation engine s...
stable/apm-server                        2.1.7            7.0.0                      DEPRECATED The server receives data from the Elastic APM ...
[machangwei@mcwk8s-master ~]$ helm search  #可安装chart
NAME                                     CHART VERSION    APP VERSION                DESCRIPTION                                                 
stable/acs-engine-autoscaler             2.2.2            2.1.1                      DEPRECATED Scales worker nodes within agent pools           
stable/aerospike                         0.3.5            v4.5.0.5                   DEPRECATED A Helm chart for Aerospike in Kubernetes         
stable/airflow                           7.13.3           1.10.12                    DEPRECATED - please use: https://github.com/airflow-helm/...
stable/ambassador                        5.3.2            0.86.1                     DEPRECATED A Helm chart for Datawire Ambassador             
stable/anchore-engine                    1.7.0            0.7.3                      Anchore container analysis and policy evaluation engine s...
stable/apm-server                        2.1.7            7.0.0                      DEPRECATED The server receives data from the Elastic APM ...
stable/ark                               4.2.2            0.10.2                     DEPRECATED A Helm chart for ark                             
stable/artifactory                       7.3.2            6.1.0                      DEPRECATED Universal Repository Manager supporting all ma...
stable/artifactory-ha                    0.4.2            6.2.0                      DEPRECATED Universal Repository Manager supporting all ma...
stable/atlantis                          3.12.4           v0.14.0                    DEPRECATED A Helm chart for Atlantis https://www.runatlan...
stable/auditbeat                         1.1.2            6.7.0                      DEPRECATED A lightweight shipper to audit the activities ...
stable/aws-cluster-autoscaler            0.3.4                                       DEPRECATED Scales worker nodes within autoscaling groups.   
stable/aws-iam-authenticator             0.1.5            1.0                        DEPRECATED A Helm chart for aws-iam-authenticator           
stable/bitcoind                          1.0.2            0.17.1                     DEPRECATED Bitcoin is an innovative payment network and a...
stable/bookstack                         1.2.4            0.27.5                     DEPRECATED BookStack is a simple, self-hosted, easy-to-us...
stable/buildkite                         0.2.4            3                          DEPRECATED Agent for Buildkite                              
stable/burrow                            1.5.4            0.29.0                     DEPRECATED Burrow is a permissionable smart contract machine
stable/centrifugo                        3.2.2            2.4.0                      DEPRECATED Centrifugo is a real-time messaging server.      
stable/cerebro                           1.9.5            0.9.2                      DEPRECATED A Helm chart for Cerebro - a web admin tool th...
stable/cert-manager                      v0.6.7           v0.6.2                     A Helm chart for cert-manager                               
stable/chaoskube                         3.3.2            0.21.0                     DEPRECATED Chaoskube periodically kills random pods in yo...
stable/chartmuseum                       2.14.2           0.12.0                     DEPRECATED Host your own Helm Chart Repository              
stable/chronograf                        1.1.1            1.7.12                     DEPRECATED Open-source web application written in Go and ...
stable/clamav                            1.0.7            1.6                        DEPRECATED An Open-Source antivirus engine for detecting ...
stable/cloudserver                       1.0.7            8.1.5                      DEPRECATED An open-source Node.js implementation of the A...
stable/cluster-autoscaler                8.0.0            1.17.1                     Scales worker nodes within autoscaling groups.              
stable/cluster-overprovisioner           0.4.1            1.0                        Installs the a deployment that overprovisions the cluster   
stable/cockroachdb                       3.0.8            19.2.5                     DEPRECATED -- CockroachDB is a scalable, survivable, stro...
stable/collabora-code                    1.0.8            4.0.3.1                    DEPRECATED A Helm chart for Collabora Office - CODE-Edition 
stable/concourse                         8.3.7            5.6.0                      DEPRECATED Concourse is a simple and scalable CI system.    
stable/consul                            3.9.6            1.5.3                      Highly available and distributed service discovery and ke...
stable/contour                           0.2.2            v0.15.0                    DEPRECATED Contour Ingress controller for Kubernetes        
stable/coredns                           1.13.8           1.7.1                      DEPRECATED CoreDNS is a DNS server that chains plugins an...
stable/cosbench                          1.0.3            0.0.6                      DEPRECATED A benchmark tool for cloud object storage serv...
stable/coscale                           1.0.2            3.16.0                     DEPRECATED CoScale Agent                                    
stable/couchbase-operator                1.0.4            1.2.2                      DEPRECATED A Helm chart to deploy the Couchbase Autonomou...
stable/couchdb                           2.3.0            2.3.1                      DEPRECATED A database featuring seamless multi-master syn...
stable/dask                              3.1.1            1.1.5                      DEPRECATED Distributed computation in Python with task sc...
stable/dask-distributed                  2.0.2                                       DEPRECATED: Distributed computation in Python               
stable/datadog                           2.3.42           7                          DEPRECATED Datadog Agent                                    
stable/dex                               2.15.2           2.24.0                     DEPRECATED OpenID Connect Identity (OIDC) and OAuth 2.0 P...
stable/distributed-jmeter                1.0.3            3.3                        DEPRECATED A Distributed JMeter Helm chart                  
stable/distributed-tensorflow            1.2.2            1.7.0                      DEPRECATED A Helm chart for running distributed TensorFlo...
stable/distribution                      0.4.3            1.1.0                      DEPRECATED A Helm chart for JFrog Distribution              
stable/dmarc2logstash                    1.3.1            1.0.3                      DEPRECATED Provides a POP3-polled DMARC XML report inject...
stable/docker-registry                   1.9.6            2.7.1                      DEPRECATED A Helm chart for Docker Registry                 
stable/dokuwiki                          6.0.11           0.20180422.201901061035    DEPRECATED DokuWiki is a standards-compliant, simple to u...
stable/drone                             2.7.2            1.6.5                      Drone is a Continuous Delivery system built on container ...
stable/drupal                            6.2.12           8.8.3                      DEPRECATED One of the most versatile open source content ...
stable/efs-provisioner                   0.13.2           v2.4.0                     DEPRECATED A Helm chart for the AWS EFS external storage ...
stable/elastabot                         1.2.1            1.1.0                      DEPRECATED A Helm chart for Elastabot - a Slack bot compa...
stable/elastalert                        1.5.1            0.2.4                      DEPRECATED ElastAlert is a simple framework for alerting ...
stable/elastic-stack                     2.0.6            6                          DEPRECATED A Helm chart for ELK                             
stable/elasticsearch                     1.32.5           6.8.6                      DEPRECATED Flexible and powerful open source, distributed...
stable/elasticsearch-curator             2.2.3            5.7.6                      DEPRECATED A Helm chart for Elasticsearch Curator           
stable/elasticsearch-exporter            3.7.1            1.1.0                      DEPRECATED Elasticsearch stats exporter for Prometheus      
stable/envoy                             1.9.4            1.11.2                     DEPRECATED Envoy is an open source edge and service proxy...
stable/etcd-operator                     0.11.2           0.9.4                      DEPRECATED CoreOS etcd-operator Helm chart for Kubernetes   
stable/ethereum                          1.0.2            v1.7.3                     DEPRECATED private Ethereum network Helm chart for Kubern...
stable/eventrouter                       0.3.2            0.3                        DEPRECATED A Helm chart for eventruter (https://github.co...
stable/express-gateway                   1.6.6            1.16.9                     DEPRECATED Express Gateway is an API Gateway that sits at...
stable/external-dns                      2.20.4           0.7.0                      DEPRECATED ExternalDNS is a Kubernetes addon that configu...
stable/factorio                          1.0.2            0.15.39                    DEPRECATED Factorio dedicated server.                       
stable/falco                             1.1.8            0.0.1                      DEPRECATED - incubator/falco                                
stable/filebeat                          4.0.2            7.4.0                      DEPRECATED A Helm chart to collect Kubernetes logs with f...
stable/fluent-bit                        2.10.3           1.3.7                      DEPRECATED Fast and Lightweight Log/Data Forwarder for Li...
stable/fluentd                           2.5.3            v2.4.0                     DEPRECATED A Fluentd Elasticsearch Helm chart for Kuberne...
stable/fluentd-elasticsearch             2.0.7            2.3.2                      DEPRECATED! - A Fluentd Helm chart for Kubernetes with El...
stable/g2                                0.3.3            0.5.0                      DEPRECATED G2 by AppsCode - Gearman in Golang               
stable/gangway                           0.4.5            3.3.0                      DEPRECATED An application that can be used to easily enab...
stable/gce-ingress                       1.2.2            1.4.0                      DEPRECATED A GCE Ingress Controller                         
stable/gcloud-endpoints                  0.1.2            1                          DEPRECATED Develop, deploy, protect and monitor your APIs...
stable/gcloud-sqlproxy                   0.6.1            1.11                       DEPRECATED Google Cloud SQL Proxy                           
stable/gcp-night-king                    1.0.4            1                          DEPRECATED A Helm chart for GCP Night King                  
stable/ghost                             9.1.13           3.9.0                      DEPRECATED A simple, powerful publishing platform that al...
stable/gitlab-ce                         0.2.3            9.4.1                      GitLab Community Edition                                    
stable/gitlab-ee                         0.2.3            9.4.1                      GitLab Enterprise Edition                                   
stable/gocd                              1.32.0           20.8.0                     GoCD is an open-source continuous delivery server to mode...
stable/goldpinger                        2.0.4            2.0.0                      DEPRECATED Goldpinger makes calls between its instances f...
stable/grafana                           5.5.7            7.1.1                      DEPRECATED - The leading tool for querying and visualizin...
stable/graphite                          0.2.2            1.1.5-3                    DEPRECATED! - Graphite metrics server                       
stable/graylog                           1.6.12           3.1                        DEPRECATED - Graylog is the centralized log management so...
stable/hackmd                            2.0.3            1.3.0-alpine               DEPRECATED - Realtime collaborative markdown notes on all...
stable/hadoop                            1.1.4            2.9.0                      DEPRECATED - The Apache Hadoop software library is a fram...
stable/hazelcast                         3.3.2            4.0.1                      DEPRECATED Hazelcast IMDG is the most widely used in-memo...
stable/hazelcast-jet                     1.6.2            4.1                        DEPRECATED Hazelcast Jet is an application embeddable, di...
stable/heapster                          1.0.4            1.5.4                      DEPRECATED - Heapster enables Container Cluster Monitorin...
stable/heartbeat                         1.2.2            6.7.0                      DEPRECATED - A Helm chart to periodically check the statu...
stable/helm-exporter                     0.3.3            0.4.0                      DEPRECATED Exports helm release stats to prometheus         
stable/hl-composer                       1.0.14           0.20.0                     DEPRECATED - Hyperledger Composer REST Server chart         
stable/hlf-ca                            1.2.3            1.4.3                      DEPRECATED - Hyperledger Fabric Certificate Authority cha...
stable/hlf-couchdb                       1.0.9            0.4.10                     DEPRECATED - CouchDB instance for Hyperledger Fabric (the...
stable/hlf-ord                           1.4.3            1.4.3                      DEPRECATED - Hyperledger Fabric Orderer chart (these char...
stable/hlf-peer                          1.6.3            1.4.3                      DEPRECATED - Hyperledger Fabric Peer chart (these charts ...
stable/hoard                             1.0.2            6.0.0                      DEPRECATED - Hoard is a stateless, deterministically encr...
stable/home-assistant                    0.13.4           0.108.7                    Home Assistant                                              
stable/horovod                           1.0.2            0.12.1                     DEPRECATED - A Helm chart for deploying Horovod             
stable/hubot                             1.0.4            3.3.2                      DEPRECATED - Hubot chatbot for Slack                        
stable/ignite                            1.2.2            2.7.6                      DEPRECATED - Apache Ignite is an open-source distributed ...
stable/inbucket                          3.1.2            2.0.0                      DEPRECATED - Inbucket is an email testing application       
stable/influxdb                          4.3.2            1.7.9                      DEPRECATED Scalable datastore for metrics, events, and re...
stable/ingressmonitorcontroller          1.0.50           1.0.47                     DEPRECATED - IngressMonitorController chart that runs on ...
stable/instana-agent                     1.0.35           1.1                        DEPRECATED - Instana Agent for Kubernetes                   
stable/ipfs                              0.4.4            v0.4.22                    DEPRECATED - A Helm chart for the Interplanetary File System
stable/jaeger-operator                   2.12.2           1.15.1                     jaeger-operator Helm chart for Kubernetes                   
stable/janusgraph                        0.2.6            1.0                        DEPRECATED - Open source, scalable graph database.          
stable/jasperreports                     7.0.11           7.2.0                      DEPRECATED The JasperReports server can be used as a stan...
stable/jenkins                           2.5.4            lts                        DEPRECATED - Open source continuous integration server. I...
stable/joomla                            7.1.11           3.9.15                     DEPRECATED PHP content management system (CMS) for publis...
stable/k8s-spot-rescheduler              0.4.6            v0.3.0                     DEPRECATED - A k8s-spot-rescheduler Helm chart for Kubern...
stable/k8s-spot-termination-handler      1.4.11           1.13.7-1                   DEPRECATED - The K8s Spot Termination handler handles dra...
stable/kafka-manager                     2.3.5            1.3.3.22                   DEPRECATED - A tool for managing Apache Kafka.              
stable/kanister-operator                 0.3.2            0.10.0                     DEPRECATED - Kanister-operator Helm chart for Kubernetes    
stable/kapacitor                         1.2.2            1.5.2                      DEPRECATED InfluxDB's native data processing engine. It c...
stable/karma                             1.7.2            v0.72                      DEPRECATED - A Helm chart for Karma - an UI for Prometheu...
stable/katafygio                         1.0.3            0.8.1                      DEPRECATED - Continuously backup Kubernetes objets as YAM...
stable/keel                              0.6.1            0.9.5                      DEPRECATED Open source, tool for automating Kubernetes de...
stable/keycloak                          4.10.1           5.0.0                      DEPRECATED - Open Source Identity and Access Management F...
stable/kiam                              2.5.3            3.3                        DEPRECATED Integrate AWS IAM with Kubernetes                
stable/kibana                            3.2.8            6.7.0                      DEPRECATED - Kibana is an open source data visualization ...
stable/kong                              0.36.7           1.4                        DEPRECATED The Cloud-Native Ingress and API-management      
stable/kube-hunter                       1.0.5            312                        DEPRECATED - A Helm chart for Kube-hunter                   
stable/kube-lego                         0.4.2            v0.1.6                     DEPRECATED Automatically requests certificates from Let's...
stable/kube-ops-view                     1.2.4            20.4.0                     DEPRECATED - Kubernetes Operational View - read-only syst...
stable/kube-slack                        1.3.4            v4.2.0                     DEPRECATED - Chart for kube-slack, a monitoring service f...
stable/kube-state-metrics                2.9.4            1.9.7                      DEPRECATED - Install kube-state-metrics to generate and e...
stable/kube2iam                          2.5.3            0.10.9                     DEPRECATED - Provide IAM credentials to pods based on ann...
stable/kubed                             0.3.3            0.4.0                      DEPRECATED Kubed by AppsCode - Kubernetes daemon            
stable/kubedb                            0.1.3            0.8.0-beta.2               DEPRECATED KubeDB by AppsCode - Making running production...
stable/kuberhealthy                      1.2.7            v1.0.2                     DEPRECATED. Please use https://comcast.github.io/kuberhea...
stable/kubernetes-dashboard              1.11.1           1.10.1                     DEPRECATED! - General-purpose web UI for Kubernetes clusters
stable/kuberos                           0.2.3            2018-07-03                 DEPRECATED - An OIDC authentication helper for Kubernetes   
stable/kubewatch                         1.0.9            0.0.4                      DEPRECATED Kubewatch notifies your slack rooms when chang...
stable/kured                             1.6.0            1.4.0                      DEPRECATED - A Helm chart for kured                         
stable/lamp                              1.1.6            7                          DEPRECATED - Modular and transparent LAMP stack chart sup...
stable/linkerd                           0.4.3            1.1.2                      DEPRECATED - Service mesh for cloud native apps             
stable/locust                            1.2.3            0.9.0                      DEPRECATED - A modern load testing framework                
stable/logdna-agent                      2.0.2            2.1.9                      DEPRECATED - Run this, get logs. All cluster containers. ...
stable/logstash                          2.4.3            7.1.1                      DEPRECATED - Logstash is an open source, server-side data...
stable/luigi                             2.7.8            2.7.2                      DEPRECATED Luigi is a Python module that helps you build ...
stable/magento                           6.0.0            2.3.1                      DEPRECATED A feature-rich flexible e-commerce solution. I...
stable/magic-ip-address                  0.1.2            0.9.0                      DEPRECATED - A Helm chart to assign static IP addresses f...
stable/magic-namespace                   0.6.0            2.8.1                      Elegantly enables a Tiller per namespace in RBAC-enabled ...
stable/mailhog                           2.3.1            1.0.0                      DEPRECATED - An e-mail testing tool for developers          
stable/mariadb                           7.3.14           10.3.22                    DEPRECATED Fast, reliable, scalable, and easy to use open...
stable/mattermost-team-edition           3.1.2            5.9.0                      Mattermost Team Edition server.                             
stable/mcrouter                          1.0.6            0.36.0                     DEPRECATED - Mcrouter is a memcached protocol router for ...
stable/mediawiki                         9.1.9            1.34.0                     DEPRECATED Extremely powerful, scalable software and a fe...
stable/memcached                         3.2.5            1.5.20                     DEPRECATED - Free & open source, high-performance, distri...
stable/mercure                           4.0.3            0.10.0                     DEPRECATED - The Mercure hub allows to push data updates ...
stable/metabase                          0.13.2           v0.36.3                    DEPRECATED - The easy, open source way for everyone in yo...
stable/metallb                           0.12.1           0.8.1                      DEPRECATED MetalLB is a load-balancer implementation for ...
stable/metricbeat                        1.7.3            6.7.0                      DEPRECATED - A Helm chart to collect Kubernetes logs with...
stable/metrics-server                    2.11.4           0.3.6                      DEPRECATED - Metrics Server is a cluster-wide aggregator ...
stable/minecraft                         1.2.5            1.14.4                     Minecraft server                                            
stable/minio                             5.0.33           master                     DEPRECATED MinIO is a high performance data infrastructur...
stable/mission-control                   0.4.4            3.1.2                      DEPRECATED A Helm chart for JFrog Mission Control           
stable/mongodb                           7.8.10           4.2.4                      DEPRECATED NoSQL document-oriented database that stores J...
stable/mongodb-replicaset                3.17.2           3.6                        DEPRECATED - NoSQL document-oriented database that stores...
stable/moodle                            7.2.8            3.8.2                      DEPRECATED Moodle is a learning platform designed to prov...
stable/msoms                             0.2.2            1.0.0-30                   DEPRECATED - A chart for deploying omsagent as a daemonse...
stable/mssql-linux                       0.11.4           14.0.3023.8                DEPRECATED - SQL Server 2017 Linux Helm Chart               
stable/mysql                             1.6.9            5.7.30                     DEPRECATED - Fast, reliable, scalable, and easy to use op...
stable/mysqldump                         2.6.2            2.4.1                      DEPRECATED! - A Helm chart to help backup MySQL databases...
stable/namerd                            0.2.2            0.9.1                      DEPRECATED - Service that manages routing for multiple li...
stable/nats                              4.3.7            2.1.4                      DEPRECATED An open-source, cloud-native messaging system    
stable/neo4j                             3.0.1            4.0.4                      DEPRECATED Neo4j is the world's leading graph database      
stable/newrelic-infrastructure           0.13.36          1.21.0                     DEPRECATED - A Helm chart to deploy the New Relic Infrast...
stable/nextcloud                         1.12.1           17.0.0                     DEPRECATED - A file sharing server that puts the control ...
stable/nfs-client-provisioner            1.2.11           3.1.0                      DEPRECATED - nfs-client is an automatic provisioner that ...
stable/nfs-server-provisioner            1.1.3            2.3.0                      DEPRECATED - nfs-server-provisioner is an out-of-tree dyn...
stable/nginx-ingress                     1.41.3           v0.34.1                    DEPRECATED! An nginx Ingress controller that uses ConfigM...
stable/nginx-ldapauth-proxy              0.1.6            1.13.5                     DEPRECATED - nginx proxy with ldapauth                      
stable/nginx-lego                        0.3.1                                       Chart for nginx-ingress-controller and kube-lego            
stable/node-problem-detector             1.8.3            v0.8.1                     DEPRECATED - Installs the node-problem-detector daemonset...
stable/node-red                          1.4.3            1.0.4                      Node-RED is low-code programming for event-driven applica...
stable/oauth2-proxy                      3.2.5            5.1.0                      DEPRECATED - A reverse proxy that provides authentication...
stable/odoo                              13.0.5           12.0.20200215              DEPRECATED A suite of web based open source business apps.  
stable/opa                               1.14.6           0.15.1                     DEPRECATED - Open source, general-purpose policy engine. ...
stable/opencart                          7.0.8            3.0.3-2                    DEPRECATED A free and open source e-commerce platform for...
stable/openebs                           1.11.1           1.11.0                     DEPRECATED Containerized Storage for Containers             
stable/openiban                          1.0.2            1.0.1                      DEPRECATED - OpenIBAN is a self-hosted, free and open-sou...
stable/openldap                          1.2.7            2.4.48                     DEPRECATED - Community developed LDAP software              
stable/openvpn                           4.2.5            1.1.0                      DEPRECATED - A Helm chart to install an openvpn server in...
stable/orangehrm                         7.0.10           4.3.4-0                    DEPRECATED OrangeHRM is a free HR management system that ...
stable/osclass                           7.0.10           3.7.4                      DEPRECATED Osclass is a php script that allows you to qui...
stable/owncloud                          8.1.8            10.4.0                     DEPRECATED A file sharing server that puts the control an...
stable/pachyderm                         0.2.3            1.8.6                      DEPRECATED - Pachyderm is a large-scale container-based w...
stable/parse                             10.3.10          3.10.0                     DEPRECATED Parse is a platform that enables users to add ...
stable/percona                           1.2.3            5.7.26                     DEPRECATED - free, fully compatible, enhanced, open sourc...
stable/percona-xtradb-cluster            1.0.8            5.7.19                     DEPRECATED - free, fully compatible, enhanced, open sourc...
stable/pgadmin                           1.2.3            4.18.0                     DEPRECATED - moved to new repo, see source for new location 
stable/phabricator                       9.0.13           2020.7.0                   DEPRECATED Collection of open source web applications tha...
stable/phpbb                             7.0.10           3.3.0                      DEPRECATED Community forum that supports the notion of us...
stable/phpmyadmin                        4.3.5            5.0.1                      DEPRECATED phpMyAdmin is an mysql administration frontend   
stable/pomerium                          4.2.6            0.5.2                      DEPRECATED - see https://helm.pomerium.io                   
stable/postgresql                        8.6.4            11.7.0                     DEPRECATED Chart for PostgreSQL, an object-relational dat...
stable/prestashop                        9.1.11           1.7.6-4                    DEPRECATED A popular open source ecommerce solution. Prof...
stable/presto                            0.2.3            329                        DEPRECATED - Distributed SQL query engine for running int...
stable/prisma                            1.2.4            1.29.1                     DEPRECATED Prisma turns your database into a realtime Gra...
stable/prometheus                        11.12.1          2.20.1                     DEPRECATED Prometheus is a monitoring system and time ser...
stable/prometheus-adapter                2.5.1            v0.7.0                     DEPRECATED A Helm chart for k8s prometheus adapter          
stable/prometheus-blackbox-exporter      4.3.1            0.16.0                     DEPRECATED Prometheus Blackbox Exporter                     
stable/prometheus-cloudwatch-exporter    0.8.4            0.8.0                      DEPRECATED A Helm chart for prometheus cloudwatch-exporter  
stable/prometheus-consul-exporter        0.1.6            0.4.0                      DEPRECATED A Helm chart for the Prometheus Consul Exporter  
stable/prometheus-couchdb-exporter       0.1.2            1.0                        DEPRECATED A Helm chart to export the metrics from couchd...
stable/prometheus-mongodb-exporter       2.8.1            v0.10.0                    DEPRECATED A Prometheus exporter for MongoDB metrics        
stable/prometheus-mysql-exporter         0.7.1            v0.11.0                    DEPRECATED A Helm chart for prometheus mysql exporter wit...
stable/prometheus-nats-exporter          2.5.1            0.6.2                      DEPRECATED A Helm chart for prometheus-nats-exporter        
stable/prometheus-node-exporter          1.11.2           1.0.1                      DEPRECATED A Helm chart for prometheus node-exporter        
stable/prometheus-operator               9.3.2            0.38.1                     DEPRECATED Provides easy monitoring definitions for Kuber...
stable/prometheus-postgres-exporter      1.3.1            0.8.0                      DEPRECATED A Helm chart for prometheus postgres-exporter    
stable/prometheus-pushgateway            1.4.3            1.2.0                      DEPRECATED A Helm chart for prometheus pushgateway          
stable/prometheus-rabbitmq-exporter      0.5.6            v0.29.0                    DEPRECATED Rabbitmq metrics exporter for prometheus         
stable/prometheus-redis-exporter         3.5.1            1.3.4                      DEPRECATED Prometheus exporter for Redis metrics            
stable/prometheus-snmp-exporter          0.0.6            0.14.0                     DEPRECATED Prometheus SNMP Exporter                         
stable/prometheus-to-sd                  0.3.1            0.5.2                      DEPRECATED Scrape metrics stored in prometheus format and...
stable/quassel                           0.2.13           0.13.1                     DEPRECATED - Quassel IRC is a modern, cross-platform, dis...
stable/rabbitmq                          6.18.2           3.8.2                      DEPRECATED Open source message broker software that imple...
stable/rabbitmq-ha                       1.47.1           3.8.7                      DEPRECATED - Highly available RabbitMQ cluster, the open ...
stable/redis                             10.5.7           5.0.7                      DEPRECATED Open source, advanced key-value store. It is o...
stable/redis-ha                          4.4.6            5.0.6                      DEPRECATED - Highly available Kubernetes implementation o...
stable/redmine                           14.1.12          4.1.0                      DEPRECATED A flexible project management web application.   
stable/reloader                          1.3.0            v0.0.41                    DEPRECATED - Reloader chart that runs on kubernetes         
stable/rethinkdb                         1.1.4            0.1.0                      DEPRECATED - The open-source database for the realtime web  
stable/risk-advisor                      2.0.6            1.0.0                      DEPRECATED - Risk Advisor add-on module for Kubernetes      
stable/rocketchat                        2.0.10           3.6.0                      DEPRECATED - Prepare to take off with the ultimate chat p...
stable/rookout                           0.1.2            1.0                        DEPRECATED - A Helm chart for Rookout agent on Kubernetes   
stable/sapho                             0.2.4            8-jre8                     DEPRECATED A micro application development and integratio...
stable/satisfy                           1.1.2            3.0.4                      DEPRECATED - Composer repo hosting with Satisfy             
stable/schema-registry-ui                0.4.4            v0.9.5                     DEPRECATED - This is a web tool for the confluentinc/sche...
stable/sealed-secrets                    1.12.2           0.13.1                     DEPRECATED - A Helm chart for Sealed Secrets                
stable/searchlight                       0.3.3            5.0.0                      DEPRECATED Searchlight by AppsCode - Alerts for Kubernetes  
stable/selenium                          1.2.3            3.141.59                   DEPRECATED - Chart for selenium grid                        
stable/sematext-agent                    1.0.31           1.0                        DEPRECATED Helm chart for deploying Sematext Agent and Lo...
stable/sematext-docker-agent             1.0.1            1.31.53                    DEPRECATED Sematext Docker Agent                            
stable/sensu                             0.2.5            0.28                       DEPRECATED Sensu monitoring framework backed by the Redis...
stable/sentry                            4.3.3            9.1.2                      DEPRECATED - Sentry is a cross-platform crash reporting a...
stable/seq                               2.3.2            2020                       DEPRECATED - Seq is the easiest way for development teams...
stable/signalfx-agent                    0.3.1            3.6.1                      DEPRECATED The SignalFx Kubernetes agent                    
stable/signalsciences                    2.0.2            4.5.0                      DEPRECATED - SignalSciences is a web application firewall...
stable/socat-tunneller                   0.1.2            1.0                        DEPRECATED - A Helm chart for socat-tunneller               
stable/sonarqube                         4.0.1            7.9.2                      DEPRECATED SonarQube is an open sourced code quality scan...
stable/sonatype-nexus                    1.23.1           3.20.1-01                  DEPRECATED - Sonatype Nexus is an open source repository ...
stable/spark                             1.0.5            1.5.1                      DEPRECATED - Fast and general-purpose cluster computing s...
stable/spark-history-server              1.4.3            2.4.0                      DEPRECATED - A Helm chart for Spark History Server          
stable/spartakus                         1.1.8            1.0.0                      DEPRECATED - Collect information about Kubernetes cluster...
stable/spinnaker                         2.2.6            1.16.2                     DEPRECATED - Open source, multi-cloud continuous delivery...
stable/spotify-docker-gc                 1.0.2            latest                     DEPRECATED - A simple Docker container and image garbage ...
stable/spring-cloud-data-flow            2.8.1            2.6.0                      DEPRECATED Toolkit for building data processing pipelines.  
stable/stackdriver-exporter              1.3.2            0.6.0                      DEPRECATED - Stackdriver exporter for Prometheus            
stable/stash                             0.5.3            0.7.0-rc.1                 DEPRECATED Stash by AppsCode - Backup your Kubernetes Vol...
stable/stellar-core                      1.0.2            10.0.0                     DEPRECATED Backbone node of the Stellar cryptocurrency ne...
stable/stolon                            1.6.5            0.16.0                     DEPRECATED - Stolon - PostgreSQL cloud native High Availa...
stable/sugarcrm                          1.0.7            6.5.26                     DEPRECATED SugarCRM enables businesses to create extraord...
stable/suitecrm                          8.0.11           7.11.12                    DEPRECATED SuiteCRM is a completely open source enterpris...
stable/sumokube                          1.0.2            latest                     DEPRECATED - Sumologic Log Collector                        
stable/sumologic-fluentd                 2.1.2            2.4.2                      DEPRECATED - Sumologic Log Collector                        
stable/superset                          1.1.13           0.36.0                     DEPRECATED - Apache Superset (incubating) is a modern, en...
stable/swift                             0.6.3            0.7.3                      DEPRECATED swift by AppsCode - Ajax friendly Helm Tiller ...
stable/sysdig                            1.7.16           10.0.0                     Sysdig Monitor and Secure agent                             
stable/telegraf                          1.6.1            1.12                       DEPRECATED Telegraf is an agent written in Go for collect...
stable/tensorflow-notebook               0.1.5            1.6.0                      DEPRECATED - A Helm chart for tensorflow notebook and ten...
stable/tensorflow-serving                1.1.2            1.14.0                     DEPRECATED - TensorFlow Serving is an open-source softwar...
stable/terracotta                        1.1.2            5.6.0                      DEPRECATED - Terracotta Ehcache is an improved version of...
stable/testlink                          7.1.7            1.9.20                     DEPRECATED Web-based test management system that facilita...
stable/tomcat                            0.4.3            7.0                        DEPRECATED - Deploy a basic tomcat application server wit...
stable/traefik                           1.87.7           1.7.26                     DEPRECATED - A Traefik based Kubernetes ingress controlle...
stable/uchiwa                            1.0.2            0.22                       DEPRECATED Dashboard for the Sensu monitoring framework     
stable/unbound                           1.1.4            1.6.7                      DEPRECATED - Unbound is a fast caching DNS resolver         
stable/unifi                             0.10.2           5.12.35                    DEPRECATED - Ubiquiti Network's Unifi Controller            
stable/vault-operator                    0.1.4            0.1.9                      DEPRECATED - CoreOS vault-operator Helm chart for Kubernetes
stable/velero                            2.7.4            1.2.0                      A Helm chart for velero                                     
stable/verdaccio                         0.7.8            3.11.6                     DEPRECATED - A lightweight private npm proxy registry (si...
stable/voyager                           3.2.4            6.0.0                      DEPRECATED Voyager by AppsCode - Secure Ingress Controlle...
stable/vsphere-cpi                       0.2.3            1.2.1                      DEPRECATED - A Helm chart for vSphere Cloud Provider Inte...
stable/wavefront                         1.1.2            1.0.3                      DEPRECATED Wavefront Kubernetes collector                   
stable/weave-cloud                       0.3.9            1.4.0                      DEPRECATED - Weave Cloud is a add-on to Kubernetes which ...
stable/weave-scope                       1.1.12           1.12.0                     DEPRECATED - A Helm chart for the Weave Scope cluster vis...
stable/wordpress                         9.0.3            5.3.2                      DEPRECATED Web publishing platform for building blogs and...
stable/xray                              0.4.3            2.3.0                      DEPRECATED Universal component scan for security and lice...
stable/zeppelin                          1.1.3            0.7.2                      DEPRECATED - Web-based notebook that enables data-driven,...
stable/zetcd                             0.1.11           0.0.3                      DEPRECATED CoreOS zetcd Helm chart for Kubernetes           
[machangwei@mcwk8s-master ~]$ 
可安装chart

仓库文档官网:https://docs.helm.sh/

[machangwei@mcwk8s-master ~]$ helm search mysql  #关键字搜索
NAME                                CHART VERSION    APP VERSION    DESCRIPTION                                                 
stable/mysql                        1.6.9            5.7.30         DEPRECATED - Fast, reliable, scalable, and easy to use op...
stable/mysqldump                    2.6.2            2.4.1          DEPRECATED! - A Helm chart to help backup MySQL databases...
stable/prometheus-mysql-exporter    0.7.1            v0.11.0        DEPRECATED A Helm chart for prometheus mysql exporter wit...
stable/percona                      1.2.3            5.7.26         DEPRECATED - free, fully compatible, enhanced, open sourc...
stable/percona-xtradb-cluster       1.0.8            5.7.19         DEPRECATED - free, fully compatible, enhanced, open sourc...
stable/phpmyadmin                   4.3.5            5.0.1          DEPRECATED phpMyAdmin is an mysql administration frontend   
stable/gcloud-sqlproxy              0.6.1            1.11           DEPRECATED Google Cloud SQL Proxy                           
stable/mariadb                      7.3.14           10.3.22        DEPRECATED Fast, reliable, scalable, and easy to use open...
[machangwei@mcwk8s-master ~]$  #安装,这是因为Tiller服务器权限不足
[machangwei@mcwk8s-master ~]$ helm install stable/mysql
WARNING: This chart is deprecated
Error: no available release name found

给Tiller服务添加权限

[machangwei@mcwk8s-master ~]$ kubectl create serviceaccount --namespace kube-system tiller
serviceaccount/tiller created
[machangwei@mcwk8s-master ~]$ kubectl create clusterrolebinding tiller-cluster-rule --clusterrole=cluster-admin --serviceaccount=kube-system:tiller
clusterrolebinding.rbac.authorization.k8s.io/tiller-cluster-rule created
[machangwei@mcwk8s-master ~]$ kubectl patch deploy --namespace kube-system tiller-deploy -p '{"spec":{"template":{"spec":{"serviceAccount":"tiller"}}}}'
deployment.apps/tiller-deploy patched

查看Tiller服务权限

[machangwei@mcwk8s-master ~]$ kubectl get serviceaccount
NAME      SECRETS   AGE
default   1         31d
[machangwei@mcwk8s-master ~]$ kubectl describe serviceaccount default
Name:                default
Namespace:           default
Labels:              <none>
Annotations:         <none>
Image pull secrets:  <none>
Mountable secrets:   default-token-9qbhw
Tokens:              default-token-9qbhw
Events:              <none>
[machangwei@mcwk8s-master ~]$ kubectl get serviceaccount --namespace kube-system
NAME                                 SECRETS   AGE
attachdetach-controller              1         31d
bootstrap-signer                     1         31d
certificate-controller               1         31d
clusterrole-aggregation-controller   1         31d
coredns                              1         31d
cronjob-controller                   1         31d
daemon-set-controller                1         31d
default                              1         31d
deployment-controller                1         31d
disruption-controller                1         31d
endpoint-controller                  1         31d
endpointslice-controller             1         31d
endpointslicemirroring-controller    1         31d
ephemeral-volume-controller          1         31d
expand-controller                    1         31d
flannel                              1         31d
generic-garbage-collector            1         31d
horizontal-pod-autoscaler            1         31d
job-controller                       1         31d
kube-proxy                           1         31d
namespace-controller                 1         31d
node-controller                      1         31d
persistent-volume-binder             1         31d
pod-garbage-collector                1         31d
pv-protection-controller             1         31d
pvc-protection-controller            1         31d
replicaset-controller                1         31d
replication-controller               1         31d
resourcequota-controller             1         31d
root-ca-cert-publisher               1         31d
service-account-controller           1         31d
service-controller                   1         31d
statefulset-controller               1         31d
tiller                               1         6m49s
token-cleaner                        1         31d
ttl-after-finished-controller        1         31d
ttl-controller                       1         31d
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ kubectl describe serviceaccount --namespace kube-system  tiller
Name:                tiller
Namespace:           kube-system
Labels:              <none>
Annotations:         <none>
Image pull secrets:  <none>
Mountable secrets:   tiller-token-dd6pt
Tokens:              tiller-token-dd6pt
Events:              <none>

[machangwei@mcwk8s-master ~]$ kubectl get clusterrolebinding
NAME                                                   ROLE                                                                               AGE
cluster-admin                                          ClusterRole/cluster-admin                                                          31d
flannel                                                ClusterRole/flannel                                                                31d
kubeadm:get-nodes                                      ClusterRole/kubeadm:get-nodes                                                      31d
kubeadm:kubelet-bootstrap                              ClusterRole/system:node-bootstrapper                                               31d
kubeadm:node-autoapprove-bootstrap                     ClusterRole/system:certificates.k8s.io:certificatesigningrequests:nodeclient       31d
kubeadm:node-autoapprove-certificate-rotation          ClusterRole/system:certificates.k8s.io:certificatesigningrequests:selfnodeclient   31d
kubeadm:node-proxier                                   ClusterRole/system:node-proxier                                                    31d
system:basic-user                                      ClusterRole/system:basic-user                                                      31d
system:controller:attachdetach-controller              ClusterRole/system:controller:attachdetach-controller                              31d
system:controller:certificate-controller               ClusterRole/system:controller:certificate-controller                               31d
system:controller:clusterrole-aggregation-controller   ClusterRole/system:controller:clusterrole-aggregation-controller                   31d
system:controller:cronjob-controller                   ClusterRole/system:controller:cronjob-controller                                   31d
system:controller:daemon-set-controller                ClusterRole/system:controller:daemon-set-controller                                31d
system:controller:deployment-controller                ClusterRole/system:controller:deployment-controller                                31d
system:controller:disruption-controller                ClusterRole/system:controller:disruption-controller                                31d
system:controller:endpoint-controller                  ClusterRole/system:controller:endpoint-controller                                  31d
system:controller:endpointslice-controller             ClusterRole/system:controller:endpointslice-controller                             31d
system:controller:endpointslicemirroring-controller    ClusterRole/system:controller:endpointslicemirroring-controller                    31d
system:controller:ephemeral-volume-controller          ClusterRole/system:controller:ephemeral-volume-controller                          31d
system:controller:expand-controller                    ClusterRole/system:controller:expand-controller                                    31d
system:controller:generic-garbage-collector            ClusterRole/system:controller:generic-garbage-collector                            31d
system:controller:horizontal-pod-autoscaler            ClusterRole/system:controller:horizontal-pod-autoscaler                            31d
system:controller:job-controller                       ClusterRole/system:controller:job-controller                                       31d
system:controller:namespace-controller                 ClusterRole/system:controller:namespace-controller                                 31d
system:controller:node-controller                      ClusterRole/system:controller:node-controller                                      31d
system:controller:persistent-volume-binder             ClusterRole/system:controller:persistent-volume-binder                             31d
system:controller:pod-garbage-collector                ClusterRole/system:controller:pod-garbage-collector                                31d
system:controller:pv-protection-controller             ClusterRole/system:controller:pv-protection-controller                             31d
system:controller:pvc-protection-controller            ClusterRole/system:controller:pvc-protection-controller                            31d
system:controller:replicaset-controller                ClusterRole/system:controller:replicaset-controller                                31d
system:controller:replication-controller               ClusterRole/system:controller:replication-controller                               31d
system:controller:resourcequota-controller             ClusterRole/system:controller:resourcequota-controller                             31d
system:controller:root-ca-cert-publisher               ClusterRole/system:controller:root-ca-cert-publisher                               31d
system:controller:route-controller                     ClusterRole/system:controller:route-controller                                     31d
system:controller:service-account-controller           ClusterRole/system:controller:service-account-controller                           31d
system:controller:service-controller                   ClusterRole/system:controller:service-controller                                   31d
system:controller:statefulset-controller               ClusterRole/system:controller:statefulset-controller                               31d
system:controller:ttl-after-finished-controller        ClusterRole/system:controller:ttl-after-finished-controller                        31d
system:controller:ttl-controller                       ClusterRole/system:controller:ttl-controller                                       31d
system:coredns                                         ClusterRole/system:coredns                                                         31d
system:discovery                                       ClusterRole/system:discovery                                                       31d
system:kube-controller-manager                         ClusterRole/system:kube-controller-manager                                         31d
system:kube-dns                                        ClusterRole/system:kube-dns                                                        31d
system:kube-scheduler                                  ClusterRole/system:kube-scheduler                                                  31d
system:monitoring                                      ClusterRole/system:monitoring                                                      31d
system:node                                            ClusterRole/system:node                                                            31d
system:node-proxier                                    ClusterRole/system:node-proxier                                                    31d
system:public-info-viewer                              ClusterRole/system:public-info-viewer                                              31d
system:service-account-issuer-discovery                ClusterRole/system:service-account-issuer-discovery                                31d
system:volume-scheduler                                ClusterRole/system:volume-scheduler                                                31d
tiller-cluster-rule                                    ClusterRole/cluster-admin                                                          8m12s
[machangwei@mcwk8s-master ~]$ 

再次查看刚刚做的操作进行分析,创建tiller账号,创建集群角色绑定。将kube-system下的tiller账号绑定集群角色为集群admin角色。我们部署了tiller应用。所以需要将应用授权给新建的tiller账号。即将tiller的deployment和账号tiller绑定起来。

[machangwei@mcwk8s-master ~]$ kubectl create serviceaccount --namespace kube-system tiller
serviceaccount/tiller created
[machangwei@mcwk8s-master ~]$ kubectl create clusterrolebinding tiller-cluster-rule --clusterrole=cluster-admin --serviceaccount=kube-system:tiller
clusterrolebinding.rbac.authorization.k8s.io/tiller-cluster-rule created
[machangwei@mcwk8s-master ~]$ kubectl patch deploy --namespace kube-system tiller-deploy -p '{"spec":{"template":{"spec":{"serviceAccount":"tiller"}}}}'
deployment.apps/tiller-deploy patched
[machangwei@mcwk8s-master ~]$ kubectl get deployment --namespace kube-system tiller-deploy
NAME            READY   UP-TO-DATE   AVAILABLE   AGE
tiller-deploy   1/1     1            1           48m
[machangwei@mcwk8s-master ~]$ kubectl edit deployment tiller-deploy --namespace kube-system
Edit cancelled, no changes made.
[machangwei@mcwk8s-master ~]$ 当编辑这个deployment时,就可以看到应用已经在指定的结构下有了如下键值对了 {"spec":{"template":{"spec":{"serviceAccount":"tiller"}}}}
serviceAccount: tiller

部署MySQL

[machangwei@mcwk8s-master ~]$ helm install stable/mysql
WARNING: This chart is deprecated
NAME:   kindled-guppy
LAST DEPLOYED: Mon Feb 21 02:15:09 2022
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/ConfigMap
NAME                      DATA  AGE
kindled-guppy-mysql-test  1     0s

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

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

==> v1/Pod(related)
NAME                                READY  STATUS   RESTARTS  AGE
kindled-guppy-mysql-b9c77555-n5ngw  0/1    Pending  0         0s

==> v1/Secret
NAME                 TYPE    DATA  AGE
kindled-guppy-mysql  Opaque  2     0s

==> v1/Service
NAME                 TYPE       CLUSTER-IP    EXTERNAL-IP  PORT(S)   AGE
kindled-guppy-mysql  ClusterIP  10.101.43.54  <none>       3306/TCP  0s


NOTES:
MySQL can be accessed via port 3306 on the following DNS name from within your cluster:
kindled-guppy-mysql.default.svc.cluster.local

To get your root password run:

    MYSQL_ROOT_PASSWORD=$(kubectl get secret --namespace default kindled-guppy-mysql -o jsonpath="{.data.mysql-root-password}" | base64 --decode; echo)

To connect to your database:

1. Run an Ubuntu pod that you can use as a client:

    kubectl run -i --tty ubuntu --image=ubuntu:16.04 --restart=Never -- bash -il

2. Install the mysql client:

    $ apt-get update && apt-get install mysql-client -y

3. Connect using the mysql cli, then provide your password:
    $ mysql -h kindled-guppy-mysql -p

To connect to your database directly from outside the K8s cluster:
    MYSQL_HOST=127.0.0.1
    MYSQL_PORT=3306

    # Execute the following command to route the connection:
    kubectl port-forward svc/kindled-guppy-mysql 3306

    mysql -h ${MYSQL_HOST} -P${MYSQL_PORT} -u root -p${MYSQL_ROOT_PASSWORD}
    

[machangwei@mcwk8s-master ~]$ 查看部署的各个的信息
[machangwei@mcwk8s-master ~]$ kubectl get servie kindled-guppy-mysql
error: the server doesn't have a resource type "servie"
[machangwei@mcwk8s-master ~]$ kubectl get service kindled-guppy-mysql
NAME                  TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
kindled-guppy-mysql   ClusterIP   10.101.43.54   <none>        3306/TCP   2m50s
[machangwei@mcwk8s-master ~]$ kubectl get deployment kindled-guppy-mysql
NAME                  READY   UP-TO-DATE   AVAILABLE   AGE
kindled-guppy-mysql   0/1     1            0           4m22s
[machangwei@mcwk8s-master ~]$ kubectl get pod kindled-guppy-mysql-b9c77555-n5ngw
NAME                                 READY   STATUS    RESTARTS   AGE
kindled-guppy-mysql-b9c77555-n5ngw   0/1     Pending   0          4m47s
[machangwei@mcwk8s-master ~]$ kubectl get pvc kindled-guppy-mysql #由于没有pv,所以当前release不可用
NAME                  STATUS    VOLUME   CAPACITY   ACCESS MODES   STORAGECLASS   AGE
kindled-guppy-mysql   Pending                                                     5m42s
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ helm list  #已经部署的release
NAME             REVISION    UPDATED                     STATUS      CHART          APP VERSION    NAMESPACE
kindled-guppy    1           Mon Feb 21 02:15:09 2022    DEPLOYED    mysql-1.6.9    5.7.30         default  
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ helm delete kindled-guppy  #删除

release "kindled-guppy" deleted
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ kubectl get pv  #没有pv,pod没部署起来,所以release不可用
No resources found

 chart详解

chart目录结构

[machangwei@mcwk8s-master ~]$ ls .helm/cache/  
archive
[machangwei@mcwk8s-master ~]$ ls .helm/cache/archive/  #部署了release后就有了这个包缓存
mysql-1.6.9.tgz
[machangwei@mcwk8s-master ~]$ kubectl get service  #之前删除了release,相关部署的资源都没了
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 31d
[machangwei@mcwk8s-master ~]$ kubectl get deployment
No resources found in default namespace.
[machangwei@mcwk8s-master ~]$ helm list
[machangwei@mcwk8s-master ~]$ tar xf .helm/cache/archive/mysql-1.6.9.tgz -C /tmp/
[machangwei@mcwk8s-master ~]$ ls /tmp/  
healthy kubectl-edit-3200805539.yaml systemd-private-5f46703ba8d64ed3896e6b0ce6d85f96-vgauthd.service-h1QhSc
kubectl-edit-2777326135.yaml mysql systemd-private-5f46703ba8d64ed3896e6b0ce6d85f96-vmtoolsd.service-E9nP2C
[machangwei@mcwk8s-master ~]$ ls /tmp/mysql/   #查看包里有啥文件
Chart.yaml README.md templates values.yaml
[machangwei@mcwk8s-master ~]$ ls /tmp/mysql/templates/
configurationFiles-configmap.yaml _helpers.tpl NOTES.txt secrets.yaml servicemonitor.yaml tests
deployment.yaml initializationFiles-configmap.yaml pvc.yaml serviceaccount.yaml svc.yaml
[machangwei@mcwk8s-master ~]$

[machangwei@mcwk8s-master ~]$ tree /tmp/mysql/  #目录名就是chart名字
/tmp/mysql/
├── Chart.yaml
├── README.md
├── templates
│   ├── configurationFiles-configmap.yaml
│   ├── deployment.yaml
│   ├── _helpers.tpl
│   ├── initializationFiles-configmap.yaml
│   ├── NOTES.txt
│   ├── pvc.yaml
│   ├── secrets.yaml
│   ├── serviceaccount.yaml
│   ├── servicemonitor.yaml
│   ├── svc.yaml
│   └── tests
│   ├── test-configmap.yaml
│   └── test.yaml
└── values.yaml

2 directories, 15 files
[machangwei@mcwk8s-master ~]$

apiVersion: v1
appVersion: 5.7.30
deprecated: true
description: DEPRECATED - Fast, reliable, scalable, and easy to use open-source relational
  database system.
home: https://www.mysql.com/
icon: https://www.mysql.com/common/logos/logo-mysql-170x115.png
keywords:
- mysql
- database
- sql
name: mysql
sources:
- https://github.com/kubernetes/charts
- https://github.com/docker-library/mysql
version: 1.6.9
Chart.yaml
# ⚠️ Repo Archive Notice

As of Nov 13, 2020, charts in this repo will no longer be updated.
For more information, see the Helm Charts [Deprecation and Archive Notice](https://github.com/helm/charts#%EF%B8%8F-deprecation-and-archive-notice), and [Update](https://helm.sh/blog/charts-repo-deprecation/).

# MySQL

[MySQL](https://MySQL.org) is one of the most popular database servers in the world. Notable users include Wikipedia, Facebook and Google.

## DEPRECATION NOTICE

This chart is deprecated and no longer supported.

## Introduction

This chart bootstraps a single node MySQL deployment on a [Kubernetes](http://kubernetes.io) cluster using the [Helm](https://helm.sh) package manager.

## Prerequisites

- Kubernetes 1.10+ with Beta APIs enabled
- PV provisioner support in the underlying infrastructure

## Installing the Chart

To install the chart with the release name `my-release`:

```bash
$ helm install --name my-release stable/mysql
```

The command deploys MySQL on the Kubernetes cluster in the default configuration. The [configuration](#configuration) section lists the parameters that can be configured during installation.

By default a random password will be generated for the root user. If you'd like to set your own password change the mysqlRootPassword
in the values.yaml.

You can retrieve your root password by running the following command. Make sure to replace [YOUR_RELEASE_NAME]:

    printf $(printf '\%o' `kubectl get secret [YOUR_RELEASE_NAME]-mysql -o jsonpath="{.data.mysql-root-password[*]}"`)

> **Tip**: List all releases using `helm list`

## Uninstalling the Chart

To uninstall/delete the `my-release` deployment:

```bash
$ helm delete --purge my-release
```

The command removes all the Kubernetes components associated with the chart and deletes the release completely.

## Configuration

The following table lists the configurable parameters of the MySQL chart and their default values.

| Parameter                                    | Description                                                                                  | Default                                              |
| -------------------------------------------- | -------------------------------------------------------------------------------------------- | ---------------------------------------------------- |
| `args`                                       | Additional arguments to pass to the MySQL container.                                         | `[]`                                                 |
| `initContainer.resources`                    | initContainer resource requests/limits                                                       | Memory: `10Mi`, CPU: `10m`                           |
| `image`                                      | `mysql` image repository.                                                                    | `mysql`                                              |
| `imageTag`                                   | `mysql` image tag.                                                                           | `5.7.30`                                             |
| `busybox.image`                              | `busybox` image repository.                                                                  | `busybox`                                            |
| `busybox.tag`                                | `busybox` image tag.                                                                         | `1.32`                                               |
| `testFramework.enabled`                      | `test-framework` switch.                                                                     | `true`                                               |
| `testFramework.image`                        | `test-framework` image repository.                                                           | `bats/bats`                                          |
| `testFramework.tag`                          | `test-framework` image tag.                                                                  | `1.2.1`                                              |
| `testFramework.imagePullPolicy`              | `test-framework` image pull policy.                                                          | `IfNotPresent`                                       |
| `testFramework.securityContext`              | `test-framework` securityContext                                                             | `{}`                                                 |
| `imagePullPolicy`                            | Image pull policy                                                                            | `IfNotPresent`                                       |
| `existingSecret`                             | Use Existing secret for Password details                                                     | `nil`                                                |
| `extraVolumes`                               | Additional volumes as a string to be passed to the `tpl` function                            |                                                      |
| `extraVolumeMounts`                          | Additional volumeMounts as a string to be passed to the `tpl` function                       |                                                      |
| `extraInitContainers`                        | Additional init containers as a string to be passed to the `tpl` function                    |                                                      |
| `extraEnvVars`                               | Additional environment variables as a string to be passed to the `tpl` function              |                                                      |
| `mysqlRootPassword`                          | Password for the `root` user. Ignored if existing secret is provided                         | Random 10 characters                                 |
| `mysqlUser`                                  | Username of new user to create.                                                              | `nil`                                                |
| `mysqlPassword`                              | Password for the new user. Ignored if existing secret is provided                            | Random 10 characters                                 |
| `mysqlDatabase`                              | Name for new database to create.                                                             | `nil`                                                |
| `livenessProbe.initialDelaySeconds`          | Delay before liveness probe is initiated                                                     | 30                                                   |
| `livenessProbe.periodSeconds`                | How often to perform the probe                                                               | 10                                                   |
| `livenessProbe.timeoutSeconds`               | When the probe times out                                                                     | 5                                                    |
| `livenessProbe.successThreshold`             | Minimum consecutive successes for the probe to be considered successful after having failed. | 1                                                    |
| `livenessProbe.failureThreshold`             | Minimum consecutive failures for the probe to be considered failed after having succeeded.   | 3                                                    |
| `readinessProbe.initialDelaySeconds`         | Delay before readiness probe is initiated                                                    | 5                                                    |
| `readinessProbe.periodSeconds`               | How often to perform the probe                                                               | 10                                                   |
| `readinessProbe.timeoutSeconds`              | When the probe times out                                                                     | 1                                                    |
| `readinessProbe.successThreshold`            | Minimum consecutive successes for the probe to be considered successful after having failed. | 1                                                    |
| `readinessProbe.failureThreshold`            | Minimum consecutive failures for the probe to be considered failed after having succeeded.   | 3                                                    |
| `schedulerName`                              | Name of the k8s scheduler (other than default)                                               | `nil`                                                |
| `mysqlx.port.enabled`                        | Boolean to toggle a port for mysqlx `33060` protocol.                                        | false                                                |
| `persistence.enabled`                        | Create a volume to store data                                                                | true                                                 |
| `persistence.size`                           | Size of persistent volume claim                                                              | 8Gi RW                                               |
| `persistence.storageClass`                   | Type of persistent volume claim                                                              | nil                                                  |
| `persistence.accessMode`                     | ReadWriteOnce or ReadOnly                                                                    | ReadWriteOnce                                        |
| `persistence.existingClaim`                  | Name of existing persistent volume                                                           | `nil`                                                |
| `persistence.subPath`                        | Subdirectory of the volume to mount                                                          | `nil`                                                |
| `persistence.annotations`                    | Persistent Volume annotations                                                                | {}                                                   |
| `nodeSelector`                               | Node labels for pod assignment                                                               | {}                                                   |
| `affinity`                                   | Affinity rules for pod assignment                                                            | {}                                                   |
| `tolerations`                                | Pod taint tolerations for deployment                                                         | {}                                                   |
| `metrics.enabled`                            | Start a side-car prometheus exporter                                                         | `false`                                              |
| `metrics.image`                              | Exporter image                                                                               | `prom/mysqld-exporter`                               |
| `metrics.imageTag`                           | Exporter image                                                                               | `v0.10.0`                                            |
| `metrics.imagePullPolicy`                    | Exporter image pull policy                                                                   | `IfNotPresent`                                       |
| `metrics.resources`                          | Exporter resource requests/limit                                                             | `nil`                                                |
| `metrics.livenessProbe.initialDelaySeconds`  | Delay before metrics liveness probe is initiated                                             | 15                                                   |
| `metrics.livenessProbe.timeoutSeconds`       | When the probe times out                                                                     | 5                                                    |
| `metrics.readinessProbe.initialDelaySeconds` | Delay before metrics readiness probe is initiated                                            | 5                                                    |
| `metrics.readinessProbe.timeoutSeconds`      | When the probe times out                                                                     | 1                                                    |
| `metrics.flags`                              | Additional flags for the mysql exporter to use                                               | `[]`                                                 |
| `metrics.serviceMonitor.enabled`             | Set this to `true` to create ServiceMonitor for Prometheus operator                          | `false`                                              |
| `metrics.serviceMonitor.additionalLabels`    | Additional labels that can be used so ServiceMonitor will be discovered by Prometheus        | `{}`                                                 |
| `resources`                                  | CPU/Memory resource requests/limits                                                          | Memory: `256Mi`, CPU: `100m`                         |
| `configurationFiles`                         | List of mysql configuration files                                                            | `nil`                                                |
| `configurationFilesPath`                     | Path of mysql configuration files                                                            | `/etc/mysql/conf.d/`                                 |
| `securityContext.enabled`                    | Enable security context (mysql pod)                                                          | `false`                                              |
| `securityContext.fsGroup`                    | Group ID for the container (mysql pod)                                                       | 999                                                  |
| `securityContext.runAsUser`                  | User ID for the container (mysql pod)                                                        | 999                                                  |
| `service.annotations`                        | Kubernetes annotations for mysql                                                             | {}                                                   |
| `service.type`                               | Kubernetes service type                                                                      | ClusterIP                                            |
| `service.loadBalancerIP`                     | LoadBalancer service IP                                                                      | `""`                                                 |
| `serviceAccount.create`                      | Specifies whether a ServiceAccount should be created                                         | `false`                                              |
| `serviceAccount.name`                        | The name of the ServiceAccount to create                                                     | Generated using the mysql.fullname template          |
| `ssl.enabled`                                | Setup and use SSL for MySQL connections                                                      | `false`                                              |
| `ssl.secret`                                 | Name of the secret containing the SSL certificates                                           | mysql-ssl-certs                                      |
| `ssl.certificates[0].name`                   | Name of the secret containing the SSL certificates                                           | `nil`                                                |
| `ssl.certificates[0].ca`                     | CA certificate                                                                               | `nil`                                                |
| `ssl.certificates[0].cert`                   | Server certificate (public key)                                                              | `nil`                                                |
| `ssl.certificates[0].key`                    | Server key (private key)                                                                     | `nil`                                                |
| `imagePullSecrets`                           | Name of Secret resource containing private registry credentials                              | `nil`                                                |
| `initializationFiles`                        | List of SQL files which are run after the container started                                  | `nil`                                                |
| `timezone`                                   | Container and mysqld timezone (TZ env)                                                       | `nil` (UTC depending on image)                       |
| `podAnnotations`                             | Map of annotations to add to the pods                                                        | `{}`                                                 |
| `podLabels`                                  | Map of labels to add to the pods                                                             | `{}`                                                 |
| `priorityClassName`                          | Set pod priorityClassName                                                                    | `{}`                                                 |
| `deploymentAnnotations`               | Map of annotations for deployment                                  | `{}`                               |
| `strategy`                                   | Update strategy policy                                                                       | `{type: "Recreate"}`                                 |

Some of the parameters above map to the env variables defined in the [MySQL DockerHub image](https://hub.docker.com/_/mysql/).

Specify each parameter using the `--set key=value[,key=value]` argument to `helm install`. For example,

```bash
$ helm install --name my-release \
  --set mysqlRootPassword=secretpassword,mysqlUser=my-user,mysqlPassword=my-password,mysqlDatabase=my-database \
    stable/mysql
```

The above command sets the MySQL `root` account password to `secretpassword`. Additionally it creates a standard database user named `my-user`, with the password `my-password`, who has access to a database named `my-database`.

Alternatively, a YAML file that specifies the values for the parameters can be provided while installing the chart. For example,

```bash
$ helm install --name my-release -f values.yaml stable/mysql
```

> **Tip**: You can use the default [values.yaml](values.yaml)

## Persistence

The [MySQL](https://hub.docker.com/_/mysql/) image stores the MySQL data and configurations at the `/var/lib/mysql` path of the container.

By default a PersistentVolumeClaim is created and mounted into that directory. In order to disable this functionality
you can change the values.yaml to disable persistence and use an emptyDir instead.

> *"An emptyDir volume is first created when a Pod is assigned to a Node, and exists as long as that Pod is running on that node. When a Pod is removed from a node for any reason, the data in the emptyDir is deleted forever."*

**Notice**: You may need to increase the value of `livenessProbe.initialDelaySeconds` when enabling persistence by using PersistentVolumeClaim from PersistentVolume with varying properties. Since its IO performance has impact on the database initialization performance. The default limit for database initialization is `60` seconds (`livenessProbe.initialDelaySeconds` + `livenessProbe.periodSeconds` * `livenessProbe.failureThreshold`). Once such initialization process takes more time than this limit, kubelet will restart the database container, which will interrupt database initialization then causing persisent data in an unusable state.

## Custom MySQL configuration files

The [MySQL](https://hub.docker.com/_/mysql/) image accepts custom configuration files at the path `/etc/mysql/conf.d`. If you want to use a customized MySQL configuration, you can create your alternative configuration files by passing the file contents on the `configurationFiles` attribute. Note that according to the MySQL documentation only files ending with `.cnf` are loaded.

```yaml
configurationFiles:
  mysql.cnf: |-
    [mysqld]
    skip-host-cache
    skip-name-resolve
    sql-mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
  mysql_custom.cnf: |-
    [mysqld]
```

## MySQL initialization files

The [MySQL](https://hub.docker.com/_/mysql/) image accepts *.sh, *.sql and *.sql.gz files at the path `/docker-entrypoint-initdb.d`.
These files are being run exactly once for container initialization and ignored on following container restarts.
If you want to use initialization scripts, you can create initialization files by passing the file contents on the `initializationFiles` attribute.


```yaml
initializationFiles:
  first-db.sql: |-
    CREATE DATABASE IF NOT EXISTS first DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
  second-db.sql: |-
    CREATE DATABASE IF NOT EXISTS second DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
```

## SSL

This chart supports configuring MySQL to use [encrypted connections](https://dev.mysql.com/doc/refman/5.7/en/encrypted-connections.html) with TLS/SSL certificates provided by the user. This is accomplished by storing the required Certificate Authority file, the server public key certificate, and the server private key as a Kubernetes secret. The SSL options for this chart support the following use cases:

* Manage certificate secrets with helm
* Manage certificate secrets outside of helm

## Manage certificate secrets with helm

Include your certificate data in the `ssl.certificates` section. For example:

```
ssl:
  enabled: false
  secret: mysql-ssl-certs
  certificates:
  - name: mysql-ssl-certs
    ca: |-
      -----BEGIN CERTIFICATE-----
      ...
      -----END CERTIFICATE-----
    cert: |-
      -----BEGIN CERTIFICATE-----
      ...
      -----END CERTIFICATE-----
    key: |-
      -----BEGIN RSA PRIVATE KEY-----
      ...
      -----END RSA PRIVATE KEY-----
```

> **Note**: Make sure your certificate data has the correct formatting in the values file.

## Manage certificate secrets outside of helm

1. Ensure the certificate secret exist before installation of this chart.
2. Set the name of the certificate secret in `ssl.secret`.
3. Make sure there are no entries underneath `ssl.certificates`.

To manually create the certificate secret from local files you can execute:
```
kubectl create secret generic mysql-ssl-certs \
  --from-file=ca.pem=./ssl/certificate-authority.pem \
  --from-file=server-cert.pem=./ssl/server-public-key.pem \
  --from-file=server-key.pem=./ssl/server-private-key.pem
```
> **Note**: `ca.pem`, `server-cert.pem`, and `server-key.pem` **must** be used as the key names in this generic secret.

If you are using a certificate your configurationFiles must include the three ssl lines under [mysqld]

```
[mysqld]
    ssl-ca=/ssl/ca.pem
    ssl-cert=/ssl/server-cert.pem
    ssl-key=/ssl/server-key.pem
```
README.md
## mysql image version
## ref: https://hub.docker.com/r/library/mysql/tags/
##
image: "mysql"
imageTag: "5.7.30"

strategy:
  type: Recreate

busybox:
  image: "busybox"
  tag: "1.32"

testFramework:
  enabled: true
  image: "bats/bats"
  tag: "1.2.1"
  imagePullPolicy: IfNotPresent
  securityContext: {}

## Specify password for root user
##
## Default: random 10 character string
# mysqlRootPassword: testing

## Create a database user
##
# mysqlUser:
## Default: random 10 character string
# mysqlPassword:

## Allow unauthenticated access, uncomment to enable
##
# mysqlAllowEmptyPassword: true

## Create a database
##
# mysqlDatabase:

## Specify an imagePullPolicy (Required)
## It's recommended to change this to 'Always' if the image tag is 'latest'
## ref: http://kubernetes.io/docs/user-guide/images/#updating-images
##
imagePullPolicy: IfNotPresent

## Additionnal arguments that are passed to the MySQL container.
## For example use --default-authentication-plugin=mysql_native_password if older clients need to
## connect to a MySQL 8 instance.
args: []

extraVolumes: |
  # - name: extras
  #   emptyDir: {}

extraVolumeMounts: |
  # - name: extras
  #   mountPath: /usr/share/extras
  #   readOnly: true

extraInitContainers: |
  # - name: do-something
  #   image: busybox
  #   command: ['do', 'something']

## A string to add extra environment variables
# extraEnvVars: |
#   - name: EXTRA_VAR
#     value: "extra"

# Optionally specify an array of imagePullSecrets.
# Secrets must be manually created in the namespace.
# ref: https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod
# imagePullSecrets:
  # - name: myRegistryKeySecretName

## Node selector
## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector
nodeSelector: {}

## Affinity
## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity
affinity: {}

## Tolerations for pod assignment
## Ref: https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/
##
tolerations: []

livenessProbe:
  initialDelaySeconds: 30
  periodSeconds: 10
  timeoutSeconds: 5
  successThreshold: 1
  failureThreshold: 3

readinessProbe:
  initialDelaySeconds: 5
  periodSeconds: 10
  timeoutSeconds: 1
  successThreshold: 1
  failureThreshold: 3

## Persist data to a persistent volume
persistence:
  enabled: true
  ## database data Persistent Volume Storage Class
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  # storageClass: "-"
  accessMode: ReadWriteOnce
  size: 8Gi
  annotations: {}

## Use an alternate scheduler, e.g. "stork".
## ref: https://kubernetes.io/docs/tasks/administer-cluster/configure-multiple-schedulers/
##
# schedulerName:

## Security context
securityContext:
  enabled: false
  runAsUser: 999
  fsGroup: 999

## Configure resource requests and limits
## ref: http://kubernetes.io/docs/user-guide/compute-resources/
##
resources:
  requests:
    memory: 256Mi
    cpu: 100m

# Custom mysql configuration files path
configurationFilesPath: /etc/mysql/conf.d/

# Custom mysql configuration files used to override default mysql settings
configurationFiles: {}
#  mysql.cnf: |-
#    [mysqld]
#    skip-name-resolve
#    ssl-ca=/ssl/ca.pem
#    ssl-cert=/ssl/server-cert.pem
#    ssl-key=/ssl/server-key.pem

# Custom mysql init SQL files used to initialize the database
initializationFiles: {}
#  first-db.sql: |-
#    CREATE DATABASE IF NOT EXISTS first DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
#  second-db.sql: |-
#    CREATE DATABASE IF NOT EXISTS second DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;

# To enaable the mysql X Protocol's port
# .. will expose the port 33060
# .. Note the X Plugin needs installation
# ref: https://dev.mysql.com/doc/refman/8.0/en/x-plugin-checking-installation.html
mysqlx:
  port:
    enabled: false

metrics:
  enabled: false
  image: prom/mysqld-exporter
  imageTag: v0.10.0
  imagePullPolicy: IfNotPresent
  resources: {}
  annotations: {}
    # prometheus.io/scrape: "true"
    # prometheus.io/port: "9104"
  livenessProbe:
    initialDelaySeconds: 15
    timeoutSeconds: 5
  readinessProbe:
    initialDelaySeconds: 5
    timeoutSeconds: 1
  flags: []
  serviceMonitor:
    enabled: false
    additionalLabels: {}

## Configure the service
## ref: http://kubernetes.io/docs/user-guide/services/
service:
  annotations: {}
  ## Specify a service type
  ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services---service-types
  type: ClusterIP
  port: 3306
  # nodePort: 32000
  # loadBalancerIP:

## Pods Service Account
## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
serviceAccount:
  ## Specifies whether a ServiceAccount should be created
  ##
  create: false
  ## The name of the ServiceAccount to use.
  ## If not set and create is true, a name is generated using the mariadb.fullname template
  # name:

ssl:
  enabled: false
  secret: mysql-ssl-certs
  certificates:
#  - name: mysql-ssl-certs
#    ca: |-
#      -----BEGIN CERTIFICATE-----
#      ...
#      -----END CERTIFICATE-----
#    cert: |-
#      -----BEGIN CERTIFICATE-----
#      ...
#      -----END CERTIFICATE-----
#    key: |-
#      -----BEGIN RSA PRIVATE KEY-----
#      ...
#      -----END RSA PRIVATE KEY-----

## Populates the 'TZ' system timezone environment variable
## ref: https://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html
##
## Default: nil (mysql will use image's default timezone, normally UTC)
## Example: 'Australia/Sydney'
# timezone:

# Deployment Annotations
deploymentAnnotations: {}

# To be added to the database server pod(s)
podAnnotations: {}
podLabels: {}

## Set pod priorityClassName
# priorityClassName: {}


## Init container resources defaults
initContainer:
  resources:
    requests:
      memory: 10Mi
      cpu: 10m
values.yaml
{{- if .Values.configurationFiles }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "mysql.fullname" . }}-configuration
  namespace: {{ .Release.Namespace }}
data:
{{- range $key, $val := .Values.configurationFiles }}
  {{ $key }}: |-
{{ $val | indent 4}}
{{- end }}
{{- end -}}
configurationFiles-configmap.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ template "mysql.fullname" . }}
  namespace: {{ .Release.Namespace }}
  labels:
    app: {{ template "mysql.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
{{- with .Values.deploymentAnnotations }}
  annotations:
{{ toYaml . | indent 4 }}
{{- end }}

spec:
  strategy:
{{ toYaml .Values.strategy | indent 4 }}
  selector:
    matchLabels:
      app: {{ template "mysql.fullname" . }}
      release: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app: {{ template "mysql.fullname" . }}
        release: {{ .Release.Name }}
{{- with .Values.podLabels }}
{{ toYaml . | indent 8 }}
{{- end }}
{{- with .Values.podAnnotations }}
      annotations:
{{ toYaml . | indent 8 }}
{{- end }}
    spec:
      {{- if .Values.schedulerName }}
      schedulerName: "{{ .Values.schedulerName }}"
      {{- end }}
      {{- if .Values.imagePullSecrets }}
      imagePullSecrets:
{{ toYaml .Values.imagePullSecrets | indent 8 }}
      {{- end }}
      {{- if .Values.priorityClassName }}
      priorityClassName: "{{ .Values.priorityClassName }}"
      {{- end }}
      {{- if .Values.securityContext.enabled }}
      securityContext:
        fsGroup: {{ .Values.securityContext.fsGroup }}
        runAsUser: {{ .Values.securityContext.runAsUser }}
      {{- end }}
      serviceAccountName: {{ template "mysql.serviceAccountName" . }}
      initContainers:
      - name: "remove-lost-found"
        image: "{{ .Values.busybox.image}}:{{ .Values.busybox.tag }}"
        imagePullPolicy: {{ .Values.imagePullPolicy | quote }}
        resources:
{{ toYaml .Values.initContainer.resources | indent 10 }}
        command:  ["rm", "-fr", "/var/lib/mysql/lost+found"]
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          {{- if .Values.persistence.subPath }}
          subPath: {{ .Values.persistence.subPath }}
          {{- end }}
      {{- if .Values.extraInitContainers }}
{{ tpl .Values.extraInitContainers . | indent 6 }}
      {{- end }}
      {{- if .Values.nodeSelector }}
      nodeSelector:
{{ toYaml .Values.nodeSelector | indent 8 }}
      {{- end }}
      {{- if .Values.affinity }}
      affinity:
{{ toYaml .Values.affinity | indent 8 }}
      {{- end }}
      {{- if .Values.tolerations }}
      tolerations:
{{ toYaml .Values.tolerations | indent 8 }}
      {{- end }}
      containers:
      - name: {{ template "mysql.fullname" . }}
        image: "{{ .Values.image }}:{{ .Values.imageTag }}"
        imagePullPolicy: {{ .Values.imagePullPolicy | quote }}

        {{- with .Values.args }}
        args:
        {{- range . }}
          - {{ . | quote }}
        {{- end }}
        {{- end }}
        resources:
{{ toYaml .Values.resources | indent 10 }}
        env:
        {{- if .Values.mysqlAllowEmptyPassword }}
        - name: MYSQL_ALLOW_EMPTY_PASSWORD
          value: "true"
        {{- end }}
        {{- if not (and .Values.allowEmptyRootPassword (not .Values.mysqlRootPassword)) }}
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ template "mysql.secretName" . }}
              key: mysql-root-password
              {{- if .Values.mysqlAllowEmptyPassword }}
              optional: true
              {{- end }}
        {{- end }}
        {{- if not (and .Values.allowEmptyRootPassword (not .Values.mysqlPassword)) }}
        - name: MYSQL_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ template "mysql.secretName" . }}
              key: mysql-password
              {{- if or .Values.mysqlAllowEmptyPassword (empty .Values.mysqlUser) }}
              optional: true
              {{- end }}
        {{- end }}
        - name: MYSQL_USER
          value: {{ default "" .Values.mysqlUser | quote }}
        - name: MYSQL_DATABASE
          value: {{ default "" .Values.mysqlDatabase | quote }}
        {{- if .Values.timezone }}
        - name: TZ
          value: {{ .Values.timezone }}
        {{- end }}
        {{- if .Values.extraEnvVars }}
{{ tpl .Values.extraEnvVars . | indent 8 }}
        {{- end }}
        ports:
        - name: mysql
          containerPort: 3306
        {{- if .Values.mysqlx.port.enabled }}
        - name: mysqlx
          port: 33060
        {{- end }}
        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 }}
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          {{- if .Values.persistence.subPath }}
          subPath: {{ .Values.persistence.subPath }}
          {{- end }}
        {{- if .Values.configurationFiles }}
        {{- range $key, $val := .Values.configurationFiles }}
        - name: configurations
          mountPath: {{ $.Values.configurationFilesPath }}{{ $key }}
          subPath: {{ $key }}
        {{- end -}}
        {{- end }}
        {{- if .Values.initializationFiles }}
        - name: migrations
          mountPath: /docker-entrypoint-initdb.d
        {{- end }}
        {{- if .Values.ssl.enabled }}
        - name: certificates
          mountPath: /ssl
        {{- end }}
        {{- if .Values.extraVolumeMounts }}
{{ tpl .Values.extraVolumeMounts . | indent 8 }}
        {{- end }}
      {{- if .Values.metrics.enabled }}
      - name: metrics
        image: "{{ .Values.metrics.image }}:{{ .Values.metrics.imageTag }}"
        imagePullPolicy: {{ .Values.metrics.imagePullPolicy | quote }}
        {{- if .Values.mysqlAllowEmptyPassword }}
        command:
        - 'sh'
        - '-c'
        - 'DATA_SOURCE_NAME="root@(localhost:3306)/" /bin/mysqld_exporter'
        {{- else }}
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: {{ template "mysql.secretName" . }}
              key: mysql-root-password
        command:
        - 'sh'
        - '-c'
        - 'DATA_SOURCE_NAME="root:$MYSQL_ROOT_PASSWORD@(localhost:3306)/" /bin/mysqld_exporter'
        {{- end }}
        {{- range $f := .Values.metrics.flags }}
        - {{ $f | quote }}
        {{- end }}
        ports:
        - name: metrics
          containerPort: 9104
        livenessProbe:
          httpGet:
            path: /
            port: metrics
          initialDelaySeconds: {{ .Values.metrics.livenessProbe.initialDelaySeconds }}
          timeoutSeconds: {{ .Values.metrics.livenessProbe.timeoutSeconds }}
        readinessProbe:
          httpGet:
            path: /
            port: metrics
          initialDelaySeconds: {{ .Values.metrics.readinessProbe.initialDelaySeconds }}
          timeoutSeconds: {{ .Values.metrics.readinessProbe.timeoutSeconds }}
        resources:
{{ toYaml .Values.metrics.resources | indent 10 }}
      {{- end }}
      volumes:
      {{- if .Values.configurationFiles }}
      - name: configurations
        configMap:
          name: {{ template "mysql.fullname" . }}-configuration
      {{- end }}
      {{- if .Values.initializationFiles }}
      - name: migrations
        configMap:
          name: {{ template "mysql.fullname" . }}-initialization
      {{- end }}
      {{- if .Values.ssl.enabled }}
      - name: certificates
        secret:
          secretName: {{ .Values.ssl.secret }}
      {{- end }}
      - name: data
      {{- if .Values.persistence.enabled }}
        persistentVolumeClaim:
          claimName: {{ .Values.persistence.existingClaim | default (include "mysql.fullname" .) }}
      {{- else }}
        emptyDir: {}
      {{- end -}}
      {{- if .Values.extraVolumes }}
{{ tpl .Values.extraVolumes . | indent 6 }}
      {{- end }}
deployment.yaml
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "mysql.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "mysql.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- printf .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Generate chart secret name
*/}}
{{- define "mysql.secretName" -}}
{{ default (include "mysql.fullname" .) .Values.existingSecret }}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "mysql.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
{{ default (include "mysql.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
{{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}
_helpers.tpl
{{- if .Values.initializationFiles }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "mysql.fullname" . }}-initialization
  namespace: {{ .Release.Namespace }}
data:
{{- range $key, $val := .Values.initializationFiles }}
  {{ $key }}: |-
{{ $val | indent 4}}
{{- end }}
{{- end -}}
initializationFiles-configmap.yaml
MySQL can be accessed via port 3306 on the following DNS name from within your cluster:
{{ template "mysql.fullname" . }}.{{ .Release.Namespace }}.svc.cluster.local

{{- if .Values.mysqlx.port.enabled }}
Connection to the X protocol of MySQL can be done via 33060 on the following DNS name from within your cluster:
{{ template "mysql.fullname" . }}.{{ .Release.Namespace }}.svc.cluster.local
{{- end }}

{{- if .Values.existingSecret }}
If you have not already created the mysql password secret:

   kubectl create secret generic {{ .Values.existingSecret }} --namespace {{ .Release.Namespace }} --from-file=./mysql-root-password --from-file=./mysql-password
{{ else }}

To get your root password run:

    MYSQL_ROOT_PASSWORD=$(kubectl get secret --namespace {{ .Release.Namespace }} {{ template "mysql.fullname" . }} -o jsonpath="{.data.mysql-root-password}" | base64 --decode; echo)
{{- end }}

To connect to your database:

1. Run an Ubuntu pod that you can use as a client:

    kubectl run -i --tty ubuntu --image=ubuntu:16.04 --restart=Never -- bash -il

2. Install the mysql client:

    $ apt-get update && apt-get install mysql-client -y

3. Connect using the mysql cli, then provide your password:
    $ mysql -h {{ template "mysql.fullname" . }} -p

To connect to your database directly from outside the K8s cluster:
    {{- if contains "NodePort" .Values.service.type }}
    MYSQL_HOST=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath='{.items[0].status.addresses[0].address}')
    MYSQL_PORT=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ template "mysql.fullname" . }} -o jsonpath='{.spec.ports[0].nodePort}')

    {{- else if contains "ClusterIP" .Values.service.type }}
    MYSQL_HOST=127.0.0.1
    MYSQL_PORT={{ .Values.service.port }}

    # Execute the following command to route the connection:
    kubectl port-forward svc/{{ template "mysql.fullname" . }} {{ .Values.service.port }}

    {{- end }}

    mysql -h ${MYSQL_HOST} -P${MYSQL_PORT} -u root -p${MYSQL_ROOT_PASSWORD}
    
NOTES.txt
{{- if and .Values.persistence.enabled (not .Values.persistence.existingClaim) }}
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: {{ template "mysql.fullname" . }}
  namespace: {{ .Release.Namespace }}
{{- with .Values.persistence.annotations  }}
  annotations:
{{ toYaml . | indent 4 }}
{{- end }}
  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 }}
pvc.yaml
{{- if not .Values.existingSecret }}
{{- if or (not .Values.allowEmptyRootPassword) (or .Values.mysqlRootPassword .Values.mysqlPassword) }}
apiVersion: v1
kind: Secret
metadata:
  name: {{ template "mysql.fullname" . }}
  namespace: {{ .Release.Namespace }}
  labels:
    app: {{ template "mysql.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
type: Opaque
data:
  {{ if .Values.mysqlRootPassword }}
  mysql-root-password:  {{ .Values.mysqlRootPassword | b64enc | quote }}
  {{ else }}
  {{ if not .Values.allowEmptyRootPassword }}
  mysql-root-password: {{ randAlphaNum 10 | b64enc | quote }}
  {{ end }}
  {{ end }}
  {{ if .Values.mysqlPassword }}
  mysql-password:  {{ .Values.mysqlPassword | b64enc | quote }}
  {{ else }}
  {{ if not .Values.allowEmptyRootPassword }}
  mysql-password: {{ randAlphaNum 10 | b64enc | quote }}
  {{ end }}
  {{ end }}
{{ end }}
{{- if .Values.ssl.enabled }}
{{ if .Values.ssl.certificates }}
{{- range .Values.ssl.certificates }}
---
apiVersion: v1
kind: Secret
metadata:
  name: {{ .name }}
  labels:
    app: {{ template "mysql.fullname" $ }}
    chart: "{{ $.Chart.Name }}-{{ $.Chart.Version }}"
    release: "{{ $.Release.Name }}"
    heritage: "{{ $.Release.Service }}"
type: Opaque
data:
  ca.pem: {{ .ca | b64enc }}
  server-cert.pem: {{ .cert | b64enc }}
  server-key.pem: {{ .key | b64enc }}
{{- end }}
{{- end }}
{{- end }}
{{- end }}
secrets.yaml
{{- if .Values.serviceAccount.create }}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ template "mysql.serviceAccountName" . }}
  labels:
    app: {{ template "mysql.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
{{- end }}
serviceaccount.yaml
{{- if and .Values.metrics.enabled .Values.metrics.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
  name: {{ include "mysql.fullname" . }}
  namespace: {{ .Release.Namespace }}
  labels:
    app: {{ template "mysql.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
    {{- if .Values.metrics.serviceMonitor.additionalLabels }}
{{ toYaml .Values.metrics.serviceMonitor.additionalLabels | indent 4 }}
    {{- end }}
spec:
  endpoints:
    - port: metrics
      interval: 30s
  namespaceSelector:
    matchNames:
      - {{ .Release.Namespace }}
  selector:
    matchLabels:
      app: {{ include "mysql.fullname" . }}
      release: {{ .Release.Name }}
{{- end }}
servicemonitor.yaml
apiVersion: v1
kind: Service
metadata:
  name: {{ template "mysql.fullname" . }}
  namespace: {{ .Release.Namespace }}
  labels:
    app: {{ template "mysql.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    release: "{{ .Release.Name }}"
    heritage: "{{ .Release.Service }}"
  annotations:
{{- if .Values.service.annotations }}
{{ toYaml .Values.service.annotations | indent 4 }}
{{- end }}
{{- if and (.Values.metrics.enabled) (.Values.metrics.annotations) }}
{{ toYaml .Values.metrics.annotations | indent 4 }}
{{- end }}
spec:
  type: {{ .Values.service.type }}
  {{- if (and (eq .Values.service.type "LoadBalancer") (not (empty .Values.service.loadBalancerIP))) }}
  loadBalancerIP: {{ .Values.service.loadBalancerIP }}
  {{- end }}
  ports:
  - name: mysql
    port: {{ .Values.service.port }}
    targetPort: mysql
    {{- if .Values.service.nodePort }}
    nodePort: {{ .Values.service.nodePort }}
    {{- end }}
  {{- if .Values.mysqlx.port.enabled }}
  - name: mysqlx
    port: 33060
    targetPort: mysqlx
    protocol: TCP
  {{- end }}
  {{- if .Values.metrics.enabled }}
  - name: metrics
    port: 9104
    targetPort: metrics
  {{- end }}
  selector:
    app: {{ template "mysql.fullname" . }}
svc.yaml
{{- if .Values.testFramework.enabled  }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ template "mysql.fullname" . }}-test
  namespace: {{ .Release.Namespace }}
  labels:
    app: {{ template "mysql.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    heritage: "{{ .Release.Service }}"
    release: "{{ .Release.Name }}"
data:
  run.sh: |-
    {{- if .Values.ssl.enabled | and .Values.mysqlRootPassword }}
    @test "Testing SSL MySQL Connection" {
      mysql --host={{ template "mysql.fullname" . }} --port={{ .Values.service.port | default "3306" }} --ssl-cert=/ssl/server-cert.pem --ssl-key=ssl/server-key.pem -u root -p{{ .Values.mysqlRootPassword }}
    }
    {{- else if .Values.mysqlRootPassword }}
    @test "Testing MySQL Connection" {
      mysql --host={{ template "mysql.fullname" . }} --port={{ .Values.service.port | default "3306" }} -u root -p{{ .Values.mysqlRootPassword }}
    }
    {{- end }}
{{- end }}
test-configmap.yaml
{{- if .Values.testFramework.enabled  }}
apiVersion: v1
kind: Pod
metadata:
  name: {{ template "mysql.fullname" . }}-test
  namespace: {{ .Release.Namespace }}
  labels:
    app: {{ template "mysql.fullname" . }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    heritage: "{{ .Release.Service }}"
    release: "{{ .Release.Name }}"
  annotations:
    "helm.sh/hook": test-success
spec:
  {{- if .Values.testFramework.securityContext }}
  securityContext: {{ toYaml .Values.testFramework.securityContext | nindent 4 }}
  {{- end }}
  {{- if .Values.imagePullSecrets }}
  imagePullSecrets:
  {{- range .Values.imagePullSecrets }}
    - name: {{ . }}
  {{- end}}
  {{- end }}
  {{- with .Values.nodeSelector }}
  nodeSelector:
{{ toYaml . | indent 4 }}
  {{- end }}
  {{- with .Values.affinity }}
  affinity:
{{ toYaml . | indent 4 }}
  {{- end }}
  {{- with .Values.tolerations }}
  tolerations:
{{ toYaml . | indent 4 }}
  {{- end }}
  containers:
    - name: {{ .Release.Name }}-test
      image: "{{ .Values.testFramework.image }}:{{ .Values.testFramework.tag }}"
      imagePullPolicy: "{{ .Values.testFramework.imagePullPolicy}}"
      command: ["/opt/bats/bin/bats", "-t", "/tests/run.sh"]
      volumeMounts:
      - mountPath: /tests
        name: tests
        readOnly: true
      {{- if .Values.ssl.enabled }}
      - name: certificates
        mountPath: /ssl
      {{- end }}
  volumes:
  - name: tests
    configMap:
      name: {{ template "mysql.fullname" . }}-test
  {{- if .Values.ssl.enabled }}
  - name: certificates
    secret:
      secretName: {{ .Values.ssl.secret }}
  {{- end }}
  restartPolicy: Never
{{- end }}
test.yaml

chart模板

如下,可以看到是jinja2模板语言似的使用方法。{{}}调用变量,用.来寻找目录文件和文件中的yaml格式的键值。判断语句类似于jinja2,这里的是有-开头 ,而不是前后%。有时间可以写成笔记,这里的循环,判断等是怎么使用的

[machangwei@mcwk8s-master /tmp/mysql]$ tail -7 templates/tests/test.yaml 
  {{- if .Values.ssl.enabled }}
  - name: certificates
    secret:
      secretName: {{ .Values.ssl.secret }}
  {{- end }}
  restartPolicy: Never
{{- end }}
[machangwei@mcwk8s-master /tmp/mysql]$ grep -A 5 "ssl:" values.yaml 
ssl:
  enabled: false
  secret: mysql-ssl-certs
  certificates:
#  - name: mysql-ssl-certs
#    ca: |-
[machangwei@mcwk8s-master /tmp/mysql]$ 
helm install stable/mysql -n my
那么:
{{.Chart.Name}} 值为mysql
{{.Chart.Version}} 值为0.3.0
{{.Release.Name}}值为my
{{.Release.Service}} 始终取值为Tiller
{{template "mysql.fullname" .}} 计算结果为my-mysql

再次部署MySQL chart,(上一个存在问题) 

查看包中的一些信息,实际上是values.yaml的内容。
[machangwei@mcwk8s-master ~]$ helm inspect values stable/mysql

[machangwei@mcwk8s-master ~]$ helm inspect values stable/mysql
## mysql image version
## ref: https://hub.docker.com/r/library/mysql/tags/
##
image: "mysql"
imageTag: "5.7.30"

strategy:
  type: Recreate

busybox:
  image: "busybox"
  tag: "1.32"

testFramework:
  enabled: true
  image: "bats/bats"
  tag: "1.2.1"
  imagePullPolicy: IfNotPresent
  securityContext: {}

## Specify password for root user
##
## Default: random 10 character string
# mysqlRootPassword: testing

## Create a database user
##
# mysqlUser:
## Default: random 10 character string
# mysqlPassword:

## Allow unauthenticated access, uncomment to enable
##
# mysqlAllowEmptyPassword: true

## Create a database
##
# mysqlDatabase:

## Specify an imagePullPolicy (Required)
## It's recommended to change this to 'Always' if the image tag is 'latest'
## ref: http://kubernetes.io/docs/user-guide/images/#updating-images
##
imagePullPolicy: IfNotPresent

## Additionnal arguments that are passed to the MySQL container.
## For example use --default-authentication-plugin=mysql_native_password if older clients need to
## connect to a MySQL 8 instance.
args: []

extraVolumes: |
  # - name: extras
  #   emptyDir: {}

extraVolumeMounts: |
  # - name: extras
  #   mountPath: /usr/share/extras
  #   readOnly: true

extraInitContainers: |
  # - name: do-something
  #   image: busybox
  #   command: ['do', 'something']

## A string to add extra environment variables
# extraEnvVars: |
#   - name: EXTRA_VAR
#     value: "extra"

# Optionally specify an array of imagePullSecrets.
# Secrets must be manually created in the namespace.
# ref: https://kubernetes.io/docs/concepts/containers/images/#specifying-imagepullsecrets-on-a-pod
# imagePullSecrets:
  # - name: myRegistryKeySecretName

## Node selector
## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#nodeselector
nodeSelector: {}

## Affinity
## ref: https://kubernetes.io/docs/concepts/configuration/assign-pod-node/#affinity-and-anti-affinity
affinity: {}

## Tolerations for pod assignment
## Ref: https://kubernetes.io/docs/concepts/configuration/taint-and-toleration/
##
tolerations: []

livenessProbe:
  initialDelaySeconds: 30
  periodSeconds: 10
  timeoutSeconds: 5
  successThreshold: 1
  failureThreshold: 3

readinessProbe:
  initialDelaySeconds: 5
  periodSeconds: 10
  timeoutSeconds: 1
  successThreshold: 1
  failureThreshold: 3

## Persist data to a persistent volume
persistence:
  enabled: true
  ## database data Persistent Volume Storage Class
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  # storageClass: "-"
  accessMode: ReadWriteOnce
  size: 8Gi
  annotations: {}

## Use an alternate scheduler, e.g. "stork".
## ref: https://kubernetes.io/docs/tasks/administer-cluster/configure-multiple-schedulers/
##
# schedulerName:

## Security context
securityContext:
  enabled: false
  runAsUser: 999
  fsGroup: 999

## Configure resource requests and limits
## ref: http://kubernetes.io/docs/user-guide/compute-resources/
##
resources:
  requests:
    memory: 256Mi
    cpu: 100m

# Custom mysql configuration files path
configurationFilesPath: /etc/mysql/conf.d/

# Custom mysql configuration files used to override default mysql settings
configurationFiles: {}
#  mysql.cnf: |-
#    [mysqld]
#    skip-name-resolve
#    ssl-ca=/ssl/ca.pem
#    ssl-cert=/ssl/server-cert.pem
#    ssl-key=/ssl/server-key.pem

# Custom mysql init SQL files used to initialize the database
initializationFiles: {}
#  first-db.sql: |-
#    CREATE DATABASE IF NOT EXISTS first DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;
#  second-db.sql: |-
#    CREATE DATABASE IF NOT EXISTS second DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;

# To enaable the mysql X Protocol's port
# .. will expose the port 33060
# .. Note the X Plugin needs installation
# ref: https://dev.mysql.com/doc/refman/8.0/en/x-plugin-checking-installation.html
mysqlx:
  port:
    enabled: false

metrics:
  enabled: false
  image: prom/mysqld-exporter
  imageTag: v0.10.0
  imagePullPolicy: IfNotPresent
  resources: {}
  annotations: {}
    # prometheus.io/scrape: "true"
    # prometheus.io/port: "9104"
  livenessProbe:
    initialDelaySeconds: 15
    timeoutSeconds: 5
  readinessProbe:
    initialDelaySeconds: 5
    timeoutSeconds: 1
  flags: []
  serviceMonitor:
    enabled: false
    additionalLabels: {}

## Configure the service
## ref: http://kubernetes.io/docs/user-guide/services/
service:
  annotations: {}
  ## Specify a service type
  ## ref: https://kubernetes.io/docs/concepts/services-networking/service/#publishing-services---service-types
  type: ClusterIP
  port: 3306
  # nodePort: 32000
  # loadBalancerIP:

## Pods Service Account
## ref: https://kubernetes.io/docs/tasks/configure-pod-container/configure-service-account/
serviceAccount:
  ## Specifies whether a ServiceAccount should be created
  ##
  create: false
  ## The name of the ServiceAccount to use.
  ## If not set and create is true, a name is generated using the mariadb.fullname template
  # name:

ssl:
  enabled: false
  secret: mysql-ssl-certs
  certificates:
#  - name: mysql-ssl-certs
#    ca: |-
#      -----BEGIN CERTIFICATE-----
#      ...
#      -----END CERTIFICATE-----
#    cert: |-
#      -----BEGIN CERTIFICATE-----
#      ...
#      -----END CERTIFICATE-----
#    key: |-
#      -----BEGIN RSA PRIVATE KEY-----
#      ...
#      -----END RSA PRIVATE KEY-----

## Populates the 'TZ' system timezone environment variable
## ref: https://dev.mysql.com/doc/refman/5.7/en/time-zone-support.html
##
## Default: nil (mysql will use image's default timezone, normally UTC)
## Example: 'Australia/Sydney'
# timezone:

# Deployment Annotations
deploymentAnnotations: {}

# To be added to the database server pod(s)
podAnnotations: {}
podLabels: {}

## Set pod priorityClassName
# priorityClassName: {}


## Init container resources defaults
initContainer:
  resources:
    requests:
      memory: 10Mi
      cpu: 10m

[machangwei@mcwk8s-master ~]$ 
View Code
可以看到配置中需要一个8G的pv,由于使用环境不支持动态供给,于是手动创建pv
## Persist data to a persistent volume
persistence:
  enabled: true
  ## database data Persistent Volume Storage Class
  ## If defined, storageClassName: <storageClass>
  ## If set to "-", storageClassName: "", which disables dynamic provisioning
  ## If undefined (the default) or set to null, no storageClassName spec is
  ##   set, choosing the default provisioner.  (gp2 on AWS, standard on
  ##   GKE, AWS & OpenStack)
  ##
  # storageClass: "-"
  accessMode: ReadWriteOnce
  size: 8Gi
  annotations: {}

预先创建pv
 [machangwei@mcwk8s-master ~]$ cat mysqlPv.yml 
apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysql-pv
spec:
  accessModes:
    - ReadWriteOnce
  capacity:
    storage: 8Gi
  persistentVolumeReclaimPolicy: Retain
#    storageClassName: nfs
  nfs:
    path: /nfsdata/mysql-pv
    server: 10.0.0.4
[machangwei@mcwk8s-master ~]$ kubectl apply -f mysqlPv.yml 
persistentvolume/mysql-pv created
[machangwei@mcwk8s-master ~]$ kubectl get pv
NAME       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS      CLAIM   STORAGECLASS   REASON   AGE
mysql-pv   8Gi        RWO            Retain           Available                                   6s

定制化安装chart。如下两种方法
1、定制化安装chart。可以
helm inspect values mysql > myvalues.yaml   #生成values文件
然后设置mysqlRootPassword ,最后执行如下:指定使用修改后的values文件
helm install --values=myvalues.yaml mysql 
2、--set传参方式
release是定义的my,其它各类资源名称都是my-mysql
[machangwei@mcwk8s-master ~]$ helm install stable/mysql --set mysqlRootPassword=abc123 -n my
WARNING: This chart is deprecated
NAME:   my
LAST DEPLOYED: Mon Feb 21 14:44:27 2022
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/ConfigMap
NAME           DATA  AGE
my-mysql-test  1     9s

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

==> v1/PersistentVolumeClaim
NAME      STATUS  VOLUME    CAPACITY  ACCESS MODES  STORAGECLASS  AGE
my-mysql  Bound   mysql-pv  8Gi       RWO           9s

==> v1/Pod(related)
NAME                       READY  STATUS   RESTARTS  AGE
my-mysql-857b76d499-5mjsk  0/1    Pending  0         4s

==> v1/Secret
NAME      TYPE    DATA  AGE
my-mysql  Opaque  2     9s

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


NOTES:
MySQL can be accessed via port 3306 on the following DNS name from within your cluster:
my-mysql.default.svc.cluster.local

To get your root password run:

    MYSQL_ROOT_PASSWORD=$(kubectl get secret --namespace default my-mysql -o jsonpath="{.data.mysql-root-password}" | base64 --decode; echo)

To connect to your database:

1. Run an Ubuntu pod that you can use as a client:

    kubectl run -i --tty ubuntu --image=ubuntu:16.04 --restart=Never -- bash -il

2. Install the mysql client:

    $ apt-get update && apt-get install mysql-client -y

3. Connect using the mysql cli, then provide your password:
    $ mysql -h my-mysql -p

To connect to your database directly from outside the K8s cluster:
    MYSQL_HOST=127.0.0.1
    MYSQL_PORT=3306

    # Execute the following command to route the connection:
    kubectl port-forward svc/my-mysql 3306

    mysql -h ${MYSQL_HOST} -P${MYSQL_PORT} -u root -p${MYSQL_ROOT_PASSWORD}
    

[machangwei@mcwk8s-master ~]$ 

上面查看状态发现没有部署好了,找一下原因是挂载拒绝
[machangwei@mcwk8s-master ~]$ kubectl get pod
NAME                        READY   STATUS     RESTARTS   AGE
my-mysql-857b76d499-5mjsk   0/1     Init:0/1   0          15m
[machangwei@mcwk8s-master ~]$ kubectl describe pod my-mysql-857b76d499-5mjsk
Mounting arguments: -t nfs 10.0.0.4:/nfsdata/mysql-pv /var/lib/kubelet/pods/146dae14-9e87-4306-a941-bcdd72726212/volumes/kubernetes.io~nfs/mysql-pv
Output: mount.nfs: Connection refused
  Warning  FailedMount  28s (x7 over 13m)  kubelet  Unable to attach or mount volumes: unmounted volumes=[data], unattached volumes=[data kube-api-access-k8pj5]: timed out waiting for the condition
  Normal   Pulling      14s                kubelet  Pulling image "busybox:1.32"

nfs问题

那就可能是服务没起,然后把服务启起来
[root@mcwk8s-master ~]$ ps -ef|grep nfs
root      84265  54342  0 14:59 pts/1    00:00:00 grep --color=auto nfs
[root@mcwk8s-master ~]$ ps -ef|grep rpcbind
rpc         930      1  0 10:44 ?        00:00:00 /sbin/rpcbind -w
root      84293  54342  0 14:59 pts/1    00:00:00 grep --color=auto rpcbind
[root@mcwk8s-master ~]$ systemctl start nfs

去节点上看,已经成功挂载了
[root@mcwk8s-node1 ~]$ df -h|grep mysql-pv
10.0.0.4:/nfsdata/mysql-pv   19G  4.2G   15G  23% /var/lib/kubelet/pods/146dae14-9e87-4306-a941-bcdd72726212/volumes/kubernetes.io~nfs/mysql-pv

再查看pod,发现虽然是运行,但是有错误信息和警告信息,不知道是否是有问题的
  Warning  Unhealthy    2m7s                 kubelet  Readiness probe failed: mysqladmin: [Warning] Using a password on the command line interface can be insecure.
mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
  Warning  Unhealthy  107s  kubelet  Readiness probe failed: command "sh -c mysqladmin ping -u root -p${MYSQL_ROOT_PASSWORD}" timed out
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ kubectl get pod
NAME                        READY   STATUS    RESTARTS   AGE
my-mysql-857b76d499-5mjsk   1/1     Running   0          21m
[machangwei@mcwk8s-master ~]$ ls /nfsdata/mysql-pv/  #查看,是有数据的,之前是对目录删除过得,这些是新生成的文件
auto.cnf    ca.pem           client-key.pem  ibdata1      ib_logfile1  mysql               private_key.pem  server-cert.pem  sys
ca-key.pem  client-cert.pem  ib_buffer_pool  ib_logfile0  ibtmp1       performance_schema  public_key.pem   server-key.pem


进入mysql容器
[machangwei@mcwk8s-master ~]$ kubectl get pod
NAME                        READY   STATUS    RESTARTS   AGE
my-mysql-857b76d499-5mjsk   1/1     Running   0          23m
[machangwei@mcwk8s-master ~]$ kubectl exec -it my-mysql-857b76d499-5mjsk sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
Defaulted container "my-mysql" out of: my-mysql, remove-lost-found (init)
# ls
bin  boot  dev    docker-entrypoint-initdb.d  entrypoint.sh  etc    home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
# ps -ef|grep mysql
sh: 2: ps: not found

进入MySQL两种方式

如下两种方式进入数据库
进入容器执行连接命令
[machangwei@mcwk8s-master ~]$ kubectl exec -it my-mysql-857b76d499-5mjsk sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
Defaulted container "my-mysql" out of: my-mysql, remove-lost-found (init)
# mysql -uroot -pabc123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 109
Server version: 5.7.30 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.03 sec)

mysql> 
mysql> \q
Bye
# 
[machangwei@mcwk8s-master ~]$ 

用创建一个临时的pod连接MySQL
[machangwei@mcwk8s-master ~]$ kubectl get svc
NAME         TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP    31d
my-mysql     ClusterIP   10.103.178.121   <none>        3306/TCP   30m
[machangwei@mcwk8s-master ~]$ kubectl run -it  --rm --image=mysql:5.6 --restart=Never mysql-mcwclient -- mysql -h my-mysql -pabc123  #也可以使用ip
If you don't see a command prompt, try pressing enter.
Warning: Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 150
Server version: 5.7.30 MySQL Community Server (GPL)

Copyright (c) 2000, 2021, 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> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.04 sec)

mysql> \q
Bye
pod "mysql-mcwclient" deleted
[machangwei@mcwk8s-master ~]$ 

升级和回滚release 

查看两个节点都有 5.6的镜像
[root@mcwk8s-node1 ~]$ docker images|grep mysql
mysql                                                5.6       dd3b2a5dcb48   2 months ago    303MB
mysql                                                5.7.30    9cfcce23593a   20 months ago   448MB


查看目前使用的5.7.30的镜像
[machangwei@mcwk8s-master ~]$ helm list
NAME    REVISION    UPDATED                     STATUS      CHART          APP VERSION    NAMESPACE
my      1           Mon Feb 21 14:44:27 2022    DEPLOYED    mysql-1.6.9    5.7.30         default  

当更新为5.6时,去节点上查看容器的报错信息,不支持的存储引擎,于是换成了5.7.15了
[machangwei@mcwk8s-master ~]$ helm upgrade --set imageTag=5.6 my stable/mysql
InnoDB: http://dev.mysql.com/doc/refman/5.6/en/error-creating-innodb.html
2022-02-21 07:37:42 1 [ERROR] Plugin 'InnoDB' init function returned error.
2022-02-21 07:37:42 1 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2022-02-21 07:37:42 1 [ERROR] Unknown/unsupported storage engine: InnoDB
2022-02-21 07:37:42 1 [ERROR] Aborting


当重新部署为5.7.15时,成功了
[machangwei@mcwk8s-master ~]$ helm upgrade --set imageTag=5.7.15 my stable/mysql 
......
[machangwei@mcwk8s-master ~]$ kubectl get deployment
NAME       READY   UP-TO-DATE   AVAILABLE   AGE
my-mysql   1/1     1            1           59m
[machangwei@mcwk8s-master ~]$ kubectl get deployment -o wide #deployment可以看到现在是5.7.15
NAME       READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES         SELECTOR
my-mysql   1/1     1            1           59m   my-mysql     mysql:5.7.15   app=my-mysql,release=my
[machangwei@mcwk8s-master ~]$ kubectl get  pod  -o wide
NAME                        READY   STATUS    RESTARTS   AGE     IP            NODE           NOMINATED NODE   READINESS GATES
my-mysql-7d9687dfd6-b8xfq   1/1     Running   0          4m50s   10.244.1.12   mcwk8s-node1   <none>           <none>
[machangwei@mcwk8s-master ~]$ helm list #经历了4个版本
NAME    REVISION    UPDATED                     STATUS      CHART          APP VERSION    NAMESPACE
my      4           Mon Feb 21 15:39:16 2022    DEPLOYED    mysql-1.6.9    5.7.30         default  
[machangwei@mcwk8s-master ~]$ helm history my  #其中2,3是有问题的版本,容器都没有起来。4是5.7.15版本,这里看不出来。貌似只能deployment上看
REVISION    UPDATED                     STATUS        CHART          APP VERSION    DESCRIPTION     
1           Mon Feb 21 14:44:27 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Install complete
2           Mon Feb 21 15:31:28 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Upgrade complete
3           Mon Feb 21 15:37:24 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Upgrade complete
4           Mon Feb 21 15:39:16 2022    DEPLOYED      mysql-1.6.9    5.7.30         Upgrade complete
[machangwei@mcwk8s-master ~]$ 

查看部署的节点上已经拉取到了5.7.15的镜像的
[root@mcwk8s-node1 ~]$ docker images |grep mysql
mysql                                                5.6       dd3b2a5dcb48   2 months ago    303MB
mysql                                                5.7.30    9cfcce23593a   20 months ago   448MB
mysql                                                5.7.15    18f13d72f7f0   5 years ago     383MB
[root@mcwk8s-node1 ~]$ 

进入数据库查看版本
[machangwei@mcwk8s-master ~]$ kubectl get pod
NAME                        READY   STATUS    RESTARTS   AGE
my-mysql-7d9687dfd6-b8xfq   1/1     Running   0          11m
[machangwei@mcwk8s-master ~]$ kubectl exec -it my-mysql-7d9687dfd6-b8xfq sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
Defaulted container "my-mysql" out of: my-mysql, remove-lost-found (init)
# mysql -pabc123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 119
Server version: 5.7.15 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, 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> select version();
+-----------+
| version() |
+-----------+
| 5.7.15    |
+-----------+
1 row in set (0.00 sec)

mysql> 


回滚恢复到版本1,也就是mysql版本5.7.30
[machangwei@mcwk8s-master ~]$ helm list
NAME    REVISION    UPDATED                     STATUS      CHART          APP VERSION    NAMESPACE
my      4           Mon Feb 21 15:39:16 2022    DEPLOYED    mysql-1.6.9    5.7.30         default  
[machangwei@mcwk8s-master ~]$ helm history my
REVISION    UPDATED                     STATUS        CHART          APP VERSION    DESCRIPTION     
1           Mon Feb 21 14:44:27 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Install complete
2           Mon Feb 21 15:31:28 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Upgrade complete
3           Mon Feb 21 15:37:24 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Upgrade complete
4           Mon Feb 21 15:39:16 2022    DEPLOYED      mysql-1.6.9    5.7.30         Upgrade complete
[machangwei@mcwk8s-master ~]$ helm rollback my 1
Rollback was a success.
[machangwei@mcwk8s-master ~]$ kubectl get deployment -o wide  #查看版本,回滚成功
NAME       READY   UP-TO-DATE   AVAILABLE   AGE   CONTAINERS   IMAGES         SELECTOR
my-mysql   1/1     1            1           68m   my-mysql     mysql:5.7.30   app=my-mysql,release=my
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ helm list
NAME    REVISION    UPDATED                     STATUS      CHART          APP VERSION    NAMESPACE
my      5           Mon Feb 21 15:53:02 2022    DEPLOYED    mysql-1.6.9    5.7.30         default  
[machangwei@mcwk8s-master ~]$ helm history my  #查看回滚记录
REVISION    UPDATED                     STATUS        CHART          APP VERSION    DESCRIPTION     
1           Mon Feb 21 14:44:27 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Install complete
2           Mon Feb 21 15:31:28 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Upgrade complete
3           Mon Feb 21 15:37:24 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Upgrade complete
4           Mon Feb 21 15:39:16 2022    SUPERSEDED    mysql-1.6.9    5.7.30         Upgrade complete
5           Mon Feb 21 15:53:02 2022    DEPLOYED      mysql-1.6.9    5.7.30         Rollback to 1   
[machangwei@mcwk8s-master ~]$ 


进入数据库查看版本
[machangwei@mcwk8s-master ~]$ kubectl get pod
NAME                        READY   STATUS    RESTARTS   AGE
my-mysql-857b76d499-f65g6   1/1     Running   0          60s
[machangwei@mcwk8s-master ~]$ kubectl exec -it my-mysql-857b76d499-f65g6 sh
kubectl exec [POD] [COMMAND] is DEPRECATED and will be removed in a future version. Use kubectl exec [POD] -- [COMMAND] instead.
Defaulted container "my-mysql" out of: my-mysql, remove-lost-found (init)
# mysql -pabc123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 17
Server version: 5.7.30 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, 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> select version();
+-----------+
| version() |
+-----------+
| 5.7.30    |
+-----------+
1 row in set (0.00 sec)

mysql> 

开发自己的chart 

1、创建以及查看chart文件内容

[machangwei@mcwk8s-master ~]$ ls
[machangwei@mcwk8s-master ~]$ helm create mychart
Creating mychart
[machangwei@mcwk8s-master ~]$ ls
mychart
[machangwei@mcwk8s-master ~]$ tree mychart
mychart
├── charts
├── Chart.yaml
├── templates
│   ├── deployment.yaml
│   ├── _helpers.tpl
│   ├── ingress.yaml
│   ├── NOTES.txt
│   ├── serviceaccount.yaml
│   ├── service.yaml
│   └── tests
│       └── test-connection.yaml
└── values.yaml

3 directories, 9 files
[machangwei@mcwk8s-master ~]$ cat mychart/values.yaml 
# Default values for mychart.
# This is a YAML-formatted file.
# Declare variables to be passed into your templates.

replicaCount: 1

image:
  repository: nginx
  tag: stable
  pullPolicy: IfNotPresent

imagePullSecrets: []
nameOverride: ""
fullnameOverride: ""

serviceAccount:
  # Specifies whether a service account should be created
  create: true
  # The name of the service account to use.
  # If not set and create is true, a name is generated using the fullname template
  name: ""

podSecurityContext: {}
  # fsGroup: 2000

securityContext: {}
  # capabilities:
  #   drop:
  #   - ALL
  # readOnlyRootFilesystem: true
  # runAsNonRoot: true
  # runAsUser: 1000

service:
  type: ClusterIP
  port: 80

ingress:
  enabled: false
  annotations: {}
    # kubernetes.io/ingress.class: nginx
    # kubernetes.io/tls-acme: "true"
  hosts:
    - host: chart-example.local
      paths: []

  tls: []
  #  - secretName: chart-example-tls
  #    hosts:
  #      - chart-example.local

resources: {}
  # 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: 128Mi

nodeSelector: {}

tolerations: []

affinity: {}
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ cat mychart/Chart.yaml 
apiVersion: v1
appVersion: "1.0"
description: A Helm chart for Kubernetes
name: mychart
version: 0.1.0
[machangwei@mcwk8s-master ~]$ cat mychart/templates/deployment.yaml 
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "mychart.fullname" . }}
  labels:
{{ include "mychart.labels" . | indent 4 }}
spec:
  replicas: {{ .Values.replicaCount }}
  selector:
    matchLabels:
      app.kubernetes.io/name: {{ include "mychart.name" . }}
      app.kubernetes.io/instance: {{ .Release.Name }}
  template:
    metadata:
      labels:
        app.kubernetes.io/name: {{ include "mychart.name" . }}
        app.kubernetes.io/instance: {{ .Release.Name }}
    spec:
    {{- with .Values.imagePullSecrets }}
      imagePullSecrets:
        {{- toYaml . | nindent 8 }}
    {{- end }}
      serviceAccountName: {{ template "mychart.serviceAccountName" . }}
      securityContext:
        {{- toYaml .Values.podSecurityContext | nindent 8 }}
      containers:
        - name: {{ .Chart.Name }}
          securityContext:
            {{- toYaml .Values.securityContext | nindent 12 }}
          image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
          imagePullPolicy: {{ .Values.image.pullPolicy }}
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /
              port: http
          readinessProbe:
            httpGet:
              path: /
              port: http
          resources:
            {{- toYaml .Values.resources | nindent 12 }}
      {{- with .Values.nodeSelector }}
      nodeSelector:
        {{- toYaml . | nindent 8 }}
      {{- end }}
    {{- with .Values.affinity }}
      affinity:
        {{- toYaml . | nindent 8 }}
    {{- end }}
    {{- with .Values.tolerations }}
      tolerations:
        {{- toYaml . | nindent 8 }}
    {{- end }}
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ cat mychart/templates/_helpers.tpl 
{{/* vim: set filetype=mustache: */}}
{{/*
Expand the name of the chart.
*/}}
{{- define "mychart.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Create a default fully qualified app name.
We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec).
If release name contains chart name it will be used as a full name.
*/}}
{{- define "mychart.fullname" -}}
{{- if .Values.fullnameOverride -}}
{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- $name := default .Chart.Name .Values.nameOverride -}}
{{- if contains $name .Release.Name -}}
{{- .Release.Name | trunc 63 | trimSuffix "-" -}}
{{- else -}}
{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" -}}
{{- end -}}
{{- end -}}
{{- end -}}

{{/*
Create chart name and version as used by the chart label.
*/}}
{{- define "mychart.chart" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" -}}
{{- end -}}

{{/*
Common labels
*/}}
{{- define "mychart.labels" -}}
app.kubernetes.io/name: {{ include "mychart.name" . }}
helm.sh/chart: {{ include "mychart.chart" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end -}}

{{/*
Create the name of the service account to use
*/}}
{{- define "mychart.serviceAccountName" -}}
{{- if .Values.serviceAccount.create -}}
    {{ default (include "mychart.fullname" .) .Values.serviceAccount.name }}
{{- else -}}
    {{ default "default" .Values.serviceAccount.name }}
{{- end -}}
{{- end -}}
[machangwei@mcwk8s-master ~]$ cat mychart/templates/ingress.yaml 
{{- if .Values.ingress.enabled -}}
{{- $fullName := include "mychart.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 "mychart.labels" . | indent 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 }}
[machangwei@mcwk8s-master ~]$ cat mychart/templates/NOTES.txt 
1. Get the application URL by running these commands:
{{- if .Values.ingress.enabled }}
{{- range $host := .Values.ingress.hosts }}
  {{- range .paths }}
  http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ . }}
  {{- end }}
{{- end }}
{{- else if contains "NodePort" .Values.service.type }}
  export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "mychart.fullname" . }})
  export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}")
  echo http://$NODE_IP:$NODE_PORT
{{- else if contains "LoadBalancer" .Values.service.type }}
     NOTE: It may take a few minutes for the LoadBalancer IP to be available.
           You can watch the status of by running 'kubectl get --namespace {{ .Release.Namespace }} svc -w {{ include "mychart.fullname" . }}'
  export SERVICE_IP=$(kubectl get svc --namespace {{ .Release.Namespace }} {{ include "mychart.fullname" . }} --template "{{"{{ range (index .status.loadBalancer.ingress 0) }}{{.}}{{ end }}"}}")
  echo http://$SERVICE_IP:{{ .Values.service.port }}
{{- else if contains "ClusterIP" .Values.service.type }}
  export POD_NAME=$(kubectl get pods --namespace {{ .Release.Namespace }} -l "app.kubernetes.io/name={{ include "mychart.name" . }},app.kubernetes.io/instance={{ .Release.Name }}" -o jsonpath="{.items[0].metadata.name}")
  echo "Visit http://127.0.0.1:8080 to use your application"
  kubectl port-forward $POD_NAME 8080:80
{{- end }}
[machangwei@mcwk8s-master ~]$ cat mychart/templates/serviceaccount.yaml 
{{- if .Values.serviceAccount.create -}}
apiVersion: v1
kind: ServiceAccount
metadata:
  name: {{ template "mychart.serviceAccountName" . }}
  labels:
{{ include "mychart.labels" . | indent 4 }}
{{- end -}}
[machangwei@mcwk8s-master ~]$ cat mychart/templates/service.yaml 
apiVersion: v1
kind: Service
metadata:
  name: {{ include "mychart.fullname" . }}
  labels:
{{ include "mychart.labels" . | indent 4 }}
spec:
  type: {{ .Values.service.type }}
  ports:
    - port: {{ .Values.service.port }}
      targetPort: http
      protocol: TCP
      name: http
  selector:
    app.kubernetes.io/name: {{ include "mychart.name" . }}
    app.kubernetes.io/instance: {{ .Release.Name }}
[machangwei@mcwk8s-master ~]$ cat mychart/templates/tests/test-connection.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: "{{ include "mychart.fullname" . }}-test-connection"
  labels:
{{ include "mychart.labels" . | indent 4 }}
  annotations:
    "helm.sh/hook": test-success
spec:
  containers:
    - name: wget
      image: busybox
      command: ['wget']
      args:  ['{{ include "mychart.fullname" . }}:{{ .Values.service.port }}']
  restartPolicy: Never
[machangwei@mcwk8s-master ~]$ ls mychart/charts/
[machangwei@mcwk8s-master ~]$ 

2、调试chart

[machangwei@mcwk8s-master ~]$ ls mychart/charts/
[machangwei@mcwk8s-master ~]$ vim mychart/values.yaml 
[machangwei@mcwk8s-master ~]$ sed -n "8,11p" mychart/values.yaml  #将文件改错
  repository: nginx
  tag: stable
  pullPolicy IfNotPresent

[machangwei@mcwk8s-master ~]$ ls
mychart
[machangwei@mcwk8s-master ~]$ helm lint mychart  #检查chart语法,发现错误
==> Linting mychart
[INFO] Chart.yaml: icon is recommended
[ERROR] values.yaml: unable to parse YAML
    error converting YAML to JSON: yaml: line 12: could not find expected ':'

Error: 1 chart(s) linted, 1 chart(s) failed
[machangwei@mcwk8s-master ~]$ vim mychart/values.yaml 
[machangwei@mcwk8s-master ~]$ sed -n "7,10p" mychart/values.yaml 
image:
  repository: nginx
  tag: stable
  pullPolicy: IfNotPresent
[machangwei@mcwk8s-master ~]$ helm lint mychart #改正文件再检查语法
==> Linting mychart
[INFO] Chart.yaml: icon is recommended

1 chart(s) linted, no failures
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ ls
mychart
[machangwei@mcwk8s-master ~]$ helm install --dry-run mychart --debug  #模拟安装chart,会输出米格模板生成的YAML内容。指定目录mychart
[debug] Created tunnel using local port: '15407'

[debug] SERVER: "127.0.0.1:15407"

[debug] Original chart version: ""
[debug] CHART PATH: /home/machangwei/mychart

NAME:   yucky-maltese
REVISION: 1
RELEASED: Mon Feb 21 18:01:39 2022
CHART: mychart-0.1.0
USER-SUPPLIED VALUES:
{}

COMPUTED VALUES:
affinity: {}
fullnameOverride: ""
image:
  pullPolicy: IfNotPresent
  repository: nginx
  tag: stable
imagePullSecrets: []
ingress:
  annotations: {}
  enabled: false
  hosts:
  - host: chart-example.local
    paths: []
  tls: []
nameOverride: ""
nodeSelector: {}
podSecurityContext: {}
replicaCount: 1
resources: {}
securityContext: {}
service:
  port: 80
  type: ClusterIP
serviceAccount:
  create: true
  name: ""
tolerations: []

HOOKS:
---
# yucky-maltese-mychart-test-connection
apiVersion: v1
kind: Pod
metadata:
  name: "yucky-maltese-mychart-test-connection"
  labels:
    app.kubernetes.io/name: mychart
    helm.sh/chart: mychart-0.1.0
    app.kubernetes.io/instance: yucky-maltese
    app.kubernetes.io/version: "1.0"
    app.kubernetes.io/managed-by: Tiller
  annotations:
    "helm.sh/hook": test-success
spec:
  containers:
    - name: wget
      image: busybox
      command: ['wget']
      args:  ['yucky-maltese-mychart:80']
  restartPolicy: Never
MANIFEST:

---
# Source: mychart/templates/serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: yucky-maltese-mychart
  labels:
    app.kubernetes.io/name: mychart
    helm.sh/chart: mychart-0.1.0
    app.kubernetes.io/instance: yucky-maltese
    app.kubernetes.io/version: "1.0"
    app.kubernetes.io/managed-by: Tiller
---
# Source: mychart/templates/service.yaml
apiVersion: v1
kind: Service
metadata:
  name: yucky-maltese-mychart
  labels:
    app.kubernetes.io/name: mychart
    helm.sh/chart: mychart-0.1.0
    app.kubernetes.io/instance: yucky-maltese
    app.kubernetes.io/version: "1.0"
    app.kubernetes.io/managed-by: Tiller
spec:
  type: ClusterIP
  ports:
    - port: 80
      targetPort: http
      protocol: TCP
      name: http
  selector:
    app.kubernetes.io/name: mychart
    app.kubernetes.io/instance: yucky-maltese
---
# Source: mychart/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: yucky-maltese-mychart
  labels:
    app.kubernetes.io/name: mychart
    helm.sh/chart: mychart-0.1.0
    app.kubernetes.io/instance: yucky-maltese
    app.kubernetes.io/version: "1.0"
    app.kubernetes.io/managed-by: Tiller
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: mychart
      app.kubernetes.io/instance: yucky-maltese
  template:
    metadata:
      labels:
        app.kubernetes.io/name: mychart
        app.kubernetes.io/instance: yucky-maltese
    spec:
      serviceAccountName: yucky-maltese-mychart
      securityContext:
        {}
        
      containers:
        - name: mychart
          securityContext:
            {}
            
          image: "nginx:stable"
          imagePullPolicy: IfNotPresent
          ports:
            - name: http
              containerPort: 80
              protocol: TCP
          livenessProbe:
            httpGet:
              path: /
              port: http
          readinessProbe:
            httpGet:
              path: /
              port: http
          resources:
            {}
[machangwei@mcwk8s-master ~]$

安装chart

1、仓库中的: helm install stable/nginx
2、通过tar包安装:helm install ./nginx-1.2.3.tgz
3、通过chart本地目录: helm install ./nginx
4、通过URL: helm install https://example.com/charts/nginx-1.2.3.tgz

下面是通过目录装
[machangwei@mcwk8s-master ~]$ ls 
mychart
[machangwei@mcwk8s-master ~]$ helm install mychart
NAME:   pruning-peahen
LAST DEPLOYED: Mon Feb 21 18:03:32 2022
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/Deployment
NAME                    READY  UP-TO-DATE  AVAILABLE  AGE
pruning-peahen-mychart  0/1    0           0          0s

==> v1/Pod(related)
NAME                                     READY  STATUS   RESTARTS  AGE
pruning-peahen-mychart-65b4f8889d-b2c9k  0/1    Pending  0         0s

==> v1/Service
NAME                    TYPE       CLUSTER-IP      EXTERNAL-IP  PORT(S)  AGE
pruning-peahen-mychart  ClusterIP  10.107.189.204  <none>       80/TCP   1s

==> v1/ServiceAccount
NAME                    SECRETS  AGE
pruning-peahen-mychart  1        1s


NOTES:
1. Get the application URL by running these commands:
  export POD_NAME=$(kubectl get pods --namespace default -l "app.kubernetes.io/name=mychart,app.kubernetes.io/instance=pruning-peahen" -o jsonpath="{.items[0].metadata.name}")
  echo "Visit http://127.0.0.1:8080 to use your application"
  kubectl port-forward $POD_NAME 8080:80

[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ kubectl get pod  #查看装成功了
NAME                                      READY   STATUS    RESTARTS   AGE
my-mysql-857b76d499-f65g6                 1/1     Running   0          143m
pruning-peahen-mychart-65b4f8889d-b2c9k   1/1     Running   0          12m

将chart添加到仓库 

将chart添加到仓库 

创建http服务
[root@mcwk8s-node1 ~]$ yum install nginx  
[root@mcwk8s-node1 ~]$ nginx 
[root@mcwk8s-node1 ~]$ curl -I 10.0.0.5:80
HTTP/1.1 200 OK
Server: nginx/1.20.1
Date: Mon, 21 Feb 2022 10:36:57 GMT
Content-Type: text/html
Content-Length: 4833
Last-Modified: Fri, 16 May 2014 15:12:48 GMT
Connection: keep-alive
ETag: "53762af0-12e1"
Accept-Ranges: bytes
[root@mcwk8s-node1 ~]$ ls /usr/share/nginx/html/
404.html  50x.html  en-US  icons  img  index.html  nginx-logo.png  poweredby.png


将我们写的chart目录打包
[machangwei@mcwk8s-master ~]$ ls
mychart
[machangwei@mcwk8s-master ~]$ helm package mychart
Successfully packaged chart and saved it to: /home/machangwei/mychart-0.1.0.tgz
[machangwei@mcwk8s-master ~]$ mkdir myrepo  
[machangwei@mcwk8s-master ~]$ mv mychart-0.1.0.tgz myrepo/  #将包移到新建目录下
[machangwei@mcwk8s-master ~]$ tree myrepo
myrepo
└── mychart-0.1.0.tgz

[machangwei@mcwk8s-master ~]$ helm repo index myrepo --url http://10.0.0.5:80/charts  #给目录中的包建立index,index文件记录当前仓库所以chart信息
[machangwei@mcwk8s-master ~]$ ls myrepo/
index.yaml  mychart-0.1.0.tgz
[machangwei@mcwk8s-master ~]$ cat myrepo/index.yaml  #查看仓库中chart信息
apiVersion: v1
entries:
  mychart:
  - apiVersion: v1
    appVersion: "1.0"
    created: "2022-02-21T18:41:02.718170305+08:00"
    description: A Helm chart for Kubernetes
    digest: 5160a945cc5af88ee64c5131376896af791b6ad01be74272cd2ebdadbe3da6c4
    name: mychart
    urls:
    - http://10.0.0.5:80/charts/mychart-0.1.0.tgz
    version: 0.1.0
generated: "2022-02-21T18:41:02.717147821+08:00"

将仓库中的目录上传到http服务中。

节点1上创建服务目录
[root@mcwk8s-node1 ~]$ mkdir /usr/share/nginx/html/charts/

主节点上传文件到Nginx站点目录
[machangwei@mcwk8s-master ~]$ scp -rp myrepo/* root@10.0.0.5:/usr/share/nginx/html/charts/ 
root@10.0.0.5's password: 
index.yaml                                100%  395   134.3KB/s   00:00    
mychart-0.1.0.tgz                               100% 3247     1.0MB/s   00:00 

复制到站点目录后,并不能curl访问到
[root@mcwk8s-node1 /usr/share/nginx/html]$ ls
charts  mcwbak
[root@mcwk8s-node1 /usr/share/nginx/html]$ ls charts/
index.yaml  mychart-0.1.0.tgz
[root@mcwk8s-node1 /usr/share/nginx/html]$ curl 10.0.0.5:80/charts/
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.20.1</center>
</body>
</html>
[root@mcwk8s-node1 /usr/share/nginx/html]$ 


但是主节点上搜索这个chart仓库中的chart,能搜索到
[machangwei@mcwk8s-master ~]$ helm repo add newrepo http://10.0.0.5:80/charts
"newrepo" has been added to your repositories
[machangwei@mcwk8s-master ~]$ helm repo list  #可以查看到新的chart仓库地址
NAME       URL                          
stable     https://charts.helm.sh/stable
local      http://127.0.0.1:8879/charts 
newrepo    http://10.0.0.5:80/charts    
[machangwei@mcwk8s-master ~]$ helm search mychart  #能搜索到我们创建的chart,在新建的newrepo仓库里,
NAME               CHART VERSION    APP VERSION    DESCRIPTION                
local/mychart      0.1.0            1.0            A Helm chart for Kubernetes
newrepo/mychart    0.1.0            1.0            A Helm chart for Kubernetes
[machangwei@mcwk8s-master ~]$ 


[machangwei@mcwk8s-master ~]$ helm list  #查看现在有的release
NAME              REVISION    UPDATED                     STATUS      CHART            APP VERSION    NAMESPACE
my                5           Mon Feb 21 15:53:02 2022    DEPLOYED    mysql-1.6.9      5.7.30         default  
pruning-peahen    1           Mon Feb 21 18:03:32 2022    DEPLOYED    mychart-0.1.0    1.0            default  
[machangwei@mcwk8s-master ~]$ helm delete pruning-peahen  #把这个Nginx的release删除
release "pruning-peahen" deleted
[machangwei@mcwk8s-master ~]$ kubectl get pod  #查看没有跟它相关的服务了
NAME                        READY   STATUS    RESTARTS   AGE
my-mysql-857b76d499-f65g6   1/1     Running   0          3h12m
[machangwei@mcwk8s-master ~]$ kubectl get deployment  #
NAME       READY   UP-TO-DATE   AVAILABLE   AGE
my-mysql   1/1     1            1           4h21m
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ helm install newrepo/mychart  #安装新建仓库newrepo中的mychart
NAME:   ulterior-lion
LAST DEPLOYED: Mon Feb 21 19:06:41 2022
NAMESPACE: default
STATUS: DEPLOYED

RESOURCES:
==> v1/Deployment
NAME                   READY  UP-TO-DATE  AVAILABLE  AGE
ulterior-lion-mychart  0/1    1           0          0s

==> v1/Pod(related)
NAME                                    READY  STATUS             RESTARTS  AGE
ulterior-lion-mychart-5d5fd77ccb-hwdzx  0/1    ContainerCreating  0         0s

==> v1/Service
NAME                   TYPE       CLUSTER-IP    EXTERNAL-IP  PORT(S)  AGE
ulterior-lion-mychart  ClusterIP  10.96.172.42  <none>       80/TCP   0s

==> v1/ServiceAccount
NAME                   SECRETS  AGE
ulterior-lion-mychart  1        0s


NOTES:
1. Get the application URL by running these commands:
  export POD_NAME=$(kubectl get pods --namespace default -l "app.kubernetes.io/name=mychart,app.kubernetes.io/instance=ulterior-lion" -o jsonpath="{.items[0].metadata.name}")
  echo "Visit http://127.0.0.1:8080 to use your application"
  kubectl port-forward $POD_NAME 8080:80

[machangwei@mcwk8s-master ~]$ kubectl get pod  #查看,已经成功创建并运行了pod
NAME                                     READY   STATUS    RESTARTS   AGE
my-mysql-857b76d499-f65g6                1/1     Running   0          3h15m
ulterior-lion-mychart-5d5fd77ccb-hwdzx   1/1     Running   0          2m20s
[machangwei@mcwk8s-master ~]$ 

新建chart更新到自定义chart仓库中

[machangwei@mcwk8s-master ~]$ helm create mcwchart #创建一个chart
Creating mcwchart
[machangwei@mcwk8s-master ~]$ helm package mcwchart  #将自己的chart打包
Successfully packaged chart and saved it to: /home/machangwei/mcwchart-0.1.0.tgz
[machangwei@mcwk8s-master ~]$ ls
mcwchart  mcwchart-0.1.0.tgz  mychart  myrepo
[machangwei@mcwk8s-master ~]$ scp -rp mcwchart-0.1.0.tgz root@10.0.0.5:/usr/share/nginx/html/charts
root@10.0.0.5's password: 
mcwchart-0.1.0.tgz           100% 3255     1.5MB/s   00:00    
     
去节点Nginx服务目录上查看,包已经存在了
[root@mcwk8s-node1 /usr/share/nginx/html]$ ls charts/
index.yaml  mcwchart-0.1.0.tgz  mychart-0.1.0.tgz
[root@mcwk8s-node1 /usr/share/nginx/html]$ 


更新前,newchart仓库中没有mcwchart,执行更新命令后还是没有,说明这样更新是有问题的。那么我就在主节点上将Nginx站点目录下的index文件更新,重新上传过去吧,不过这里需要保证更新index时,主节点所在的目录下有Nginx站点目录下所有包,不然就是加一个丢一堆了。
[machangwei@mcwk8s-master ~]$ helm search mcwchart
NAME              CHART VERSION    APP VERSION    DESCRIPTION                
local/mcwchart    0.1.0            1.0            A Helm chart for Kubernetes
[machangwei@mcwk8s-master ~]$ helm repo update
Hang tight while we grab the latest from your chart repositories...
...Skip local chart repository
...Successfully got an update from the "newrepo" chart repository
...Successfully got an update from the "stable" chart repository
Update Complete.
[machangwei@mcwk8s-master ~]$ helm search mcwchart
NAME              CHART VERSION    APP VERSION    DESCRIPTION                
local/mcwchart    0.1.0            1.0            A Helm chart for Kubernetes


[machangwei@mcwk8s-master ~]$ ls 
mcwchart  mcwchart-0.1.0.tgz  mychart  myrepo 
[machangwei@mcwk8s-master ~]$ mv mcwchart-0.1.0.tgz myrepo/  #将包传到这个目录下
[machangwei@mcwk8s-master ~]$ ls myrepo/ #目录下包含Nginx站点目录下的所有包,以及新加的包
index.yaml  mcwchart-0.1.0.tgz  mychart-0.1.0.tgz
[machangwei@mcwk8s-master ~]$ helm repo index myrepo/ --url http://10.0.0.5:80/charts  #根据这个目录重新创建index文件
[machangwei@mcwk8s-master ~]$ cat myrepo/index.yaml  #查看新生成的index文件,每个chart都作为entries下一个元素。
apiVersion: v1
entries:
  mcwchart:
  - apiVersion: v1
    appVersion: "1.0"
    created: "2022-02-21T19:28:03.046517034+08:00"
    description: A Helm chart for Kubernetes
    digest: b7e235d8ea60a68ab8b40d5c7fad6ccce709a25ca0dc7a603251dcb61ea4117f
    name: mcwchart
    urls:
    - http://10.0.0.5:80/charts/mcwchart-0.1.0.tgz
    version: 0.1.0
  mychart:
  - apiVersion: v1
    appVersion: "1.0"
    created: "2022-02-21T19:28:03.046966566+08:00"
    description: A Helm chart for Kubernetes
    digest: 5160a945cc5af88ee64c5131376896af791b6ad01be74272cd2ebdadbe3da6c4
    name: mychart
    urls:
    - http://10.0.0.5:80/charts/mychart-0.1.0.tgz
    version: 0.1.0
generated: "2022-02-21T19:28:03.045856607+08:00"
[machangwei@mcwk8s-master ~]$ 
[machangwei@mcwk8s-master ~]$ scp -rp myrepo/index.yaml root@10.0.0.5:/usr/share/nginx/html/charts  #之前已经将包传输过去了,现在将新的index文件传输过去
root@10.0.0.5's password: 
index.yaml                                                                                                                                                   100%  720   288.2KB/s   00:00    
[machangwei@mcwk8s-master ~]$ 


再Nginx上可以看到已经更新了index文件了
[root@mcwk8s-node1 /usr/share/nginx/html]$ ls charts/
index.yaml  mcwchart-0.1.0.tgz  mychart-0.1.0.tgz
[root@mcwk8s-node1 /usr/share/nginx/html]$ cat charts/index.yaml 
apiVersion: v1
entries:
  mcwchart:
  - apiVersion: v1
    appVersion: "1.0"
    created: "2022-02-21T19:28:03.046517034+08:00"
    description: A Helm chart for Kubernetes
    digest: b7e235d8ea60a68ab8b40d5c7fad6ccce709a25ca0dc7a603251dcb61ea4117f
    name: mcwchart
    urls:
    - http://10.0.0.5:80/charts/mcwchart-0.1.0.tgz
    version: 0.1.0
  mychart:
  - apiVersion: v1
    appVersion: "1.0"
    created: "2022-02-21T19:28:03.046966566+08:00"
    description: A Helm chart for Kubernetes
    digest: 5160a945cc5af88ee64c5131376896af791b6ad01be74272cd2ebdadbe3da6c4
    name: mychart
    urls:
    - http://10.0.0.5:80/charts/mychart-0.1.0.tgz
    version: 0.1.0
generated: "2022-02-21T19:28:03.045856607+08:00"

验证自定义仓库的更新:

[machangwei@mcwk8s-master ~]$ helm search mcwchart #虽然Nginx站点目录下更新了index文件和包。但是目前新建仓库还是无法搜索到这个新的chart
NAME              CHART VERSION    APP VERSION    DESCRIPTION                
local/mcwchart    0.1.0            1.0            A Helm chart for Kubernetes
[machangwei@mcwk8s-master ~]$ helm repo update  #helm更新一下repo
Hang tight while we grab the latest from your chart repositories...
...Skip local chart repository
...Successfully got an update from the "newrepo" chart repository
...Successfully got an update from the "stable" chart repository
Update Complete.
[machangwei@mcwk8s-master ~]$ helm search mcwchart  #再次查询,就可以看到,新建仓库newrepo中也存在新建的chart了。
NAME                CHART VERSION    APP VERSION    DESCRIPTION                
local/mcwchart      0.1.0            1.0            A Helm chart for Kubernetes
newrepo/mcwchart    0.1.0            1.0            A Helm chart for Kubernetes
[machangwei@mcwk8s-master ~]$ #也就是说必须将包传到Nginx站点目录并且更新站点目录下的index文件,然后helm repo update,才能成功更新chart到这个仓库中。

 

 

参考书籍:每天5分钟玩转kuernetes  cloudman

 

posted @ 2022-02-21 01:36  马昌伟  阅读(935)  评论(0编辑  收藏  举报
博主链接地址:https://www.cnblogs.com/machangwei-8/