龙空技术网

CKA备考实验 | 部署一个简单的mysql应用

热爱编程的通信人 94

前言:

现时姐妹们对“ubuntualternateiso”大概比较关怀,同学们都想要分析一些“ubuntualternateiso”的相关资讯。那么小编也在网摘上网罗了一些关于“ubuntualternateiso””的相关文章,希望朋友们能喜欢,你们快快来学习一下吧!

书籍来源:《CKA/CKAD应试指南:从Docker到Kubernetes完全攻略》

一边学习一边整理老师的课程内容及试验笔记,并与大家分享,侵权即删,谢谢支持!

附上汇总贴:CKA备考实验 | 汇总-CSDN博客

本章所有实验均放在一个目录helm里,先把目录helm创建出来。

步骤1:创建helm目录,并cd进去。

##########实操验证##########[root@vms10 ~]# mkdir helm[root@vms10 ~]# cd helm/[root@vms10 helm]# 

本章所有实验均在命名容间nshelm里操作,创建并切换至命名空间nshelm。

##########实操验证##########[root@vms10 helm]# kubectl create ns nshelmnamespace/nshelm created[root@vms10 helm]# [root@vms10 helm]# kubens nshelm Context "kubernetes-admin@kubernetes" modified.Active namespace is "nshelm".[root@vms10 helm]# 

步骤2:如果要部署哪个应用,就到仓库里查询这个应用对应的chart,假设要查询redis。

##########实操验证##########[root@vms10 helm]# helm search repo redisNAME                                    CHART VERSION   APP VERSION     DESCRIPTION                                       github/prometheus-redis-exporter        3.5.1           1.3.4           DEPRECATED Prometheus exporter for Redis metrics  github/redis                            10.5.7          5.0.7           DEPRECATED Open source, advanced key-value stor...github/redis-ha                         4.4.5           5.0.6           Highly available Kubernetes implementation of R...stable/redis                            1.1.15          4.0.8           Open source, advanced key-value store. It is of...stable/redis-ha                         2.0.1                           Highly available Redis cluster with multiple se...github/sensu                            0.2.3           0.28            Sensu monitoring framework backed by the Redis ...stable/sensu                            0.2.0                           Sensu monitoring framework backed by the Redis ...[root@vms10 helm]# 

如果想查询mysql对应的chart,则执行helm search repo mysql,下面开始部署mysql。

步骤3:通过helm pull把chart对应的包下载下来,命令如下。

##########实操验证##########[root@vms10 helm]# helm pull github/mysql --version=1.6.8[root@vms10 helm]# lsmysql-1.6.8.tgz[root@vms10 helm]# 

注意:这里如果不加--version选项的话,则安装的是helm源里最新的版本。

步骤4:解压并进入mysql目录。

##########实操验证##########[root@vms10 helm]# tar zxvf mysql-1.6.8.tgz mysql/Chart.yamltar: mysql/Chart.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/values.yamltar: mysql/values.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/NOTES.txttar: mysql/templates/NOTES.txt: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/_helpers.tpltar: mysql/templates/_helpers.tpl: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/configurationFiles-configmap.yamltar: mysql/templates/configurationFiles-configmap.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/deployment.yamltar: mysql/templates/deployment.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/initializationFiles-configmap.yamltar: mysql/templates/initializationFiles-configmap.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/pvc.yamltar: mysql/templates/pvc.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/secrets.yamltar: mysql/templates/secrets.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/serviceaccount.yamltar: mysql/templates/serviceaccount.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/servicemonitor.yamltar: mysql/templates/servicemonitor.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/svc.yamltar: mysql/templates/svc.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/tests/test-configmap.yamltar: mysql/templates/tests/test-configmap.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/templates/tests/test.yamltar: mysql/templates/tests/test.yaml: implausibly old time stamp 1970-01-01 08:00:00mysql/.helmignoretar: mysql/.helmignore: implausibly old time stamp 1970-01-01 08:00:00mysql/README.mdtar: mysql/README.md: implausibly old time stamp 1970-01-01 08:00:00[root@vms10 helm]# lsmysql  mysql-1.6.8.tgz[root@vms10 helm]# cd mysql/[root@vms10 mysql]# lsChart.yaml  README.md  templates  values.yaml[root@vms10 mysql]# 

Chart.yaml是chart的描述信息。

README.md是此chart的帮助信息。

templates目录里是各种模板,比如定义svc、定义pvc等。

values.yaml里记录的是chart的各种信息,比如镜像是什么,root密码是什么,是否使用持久性存储等。

步骤5:编辑values.yaml并按照如下修改。

指定要使用的镜像,按如下修改。

image: "hub.c.163.com/library/mysql"imageTag: "latest"strategy:  type: Recreate  busybox:  image: "busybox"  tag: "latest"  testFramework:  enabled:false  image: "bats/bats"  tag: "1.2.1"

上面代码中最前面的数字表示行数。

指定mysql的root密码,把最前面的#去掉,注意这里前面不能留有空格。

mysqlRootPassword: redhat 

如果要创建普通用户和密码,就修改如下两行,这里没有指定。

# mysql User:## Default: random 10 character string # mysqlPassword:

是否要使用持久性存储,如果不使用的话,就把enabled的值改成false。

persistence:  enabled: false
##########实操验证##########[root@vms10 mysql]# cat values.yaml ## mysql image version## ref: : "hub.c.163.com/library/mysql"imageTag: "latest"strategy:  type: Recreatebusybox:  image: "busybox"  tag: "latest"testFramework:  enabled: false  image: "bats/bats"  tag: "1.2.1"  imagePullPolicy: IfNotPresent  securityContext: {}## Specify password for root user#### Default: random 10 character stringmysqlRootPassword: redhat## 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: : 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: trueextraInitContainers: |  # - 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:  imagePullSecrets:  # - name: myRegistryKeySecretName## Node selector## ref: : {}## Affinity## ref: : {}## Tolerations for pod assignment## Ref: : []livenessProbe:  initialDelaySeconds: 30  periodSeconds: 10  timeoutSeconds: 5  successThreshold: 1  failureThreshold: 3readinessProbe:  initialDelaySeconds: 5  periodSeconds: 10  timeoutSeconds: 1  successThreshold: 1  failureThreshold: 3## Persist data to a persistent volumepersistence:  enabled: false  ## 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:  schedulerName:## Security contextsecurityContext:  enabled: false  runAsUser: 999  fsGroup: 999## Configure resource requests and limits## ref: :  requests:    memory: 256Mi    cpu: 100m# Custom mysql configuration files pathconfigurationFilesPath: /etc/mysql/conf.d/# Custom mysql configuration files used to override default mysql settingsconfigurationFiles: {}#  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 databaseinitializationFiles: {}#  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: :  port:    enabled: falsemetrics:  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: :  annotations: {}  ## Specify a service type  ## ref:   type: ClusterIP  port: 3306  # nodePort: 32000  # loadBalancerIP:## Pods Service Account## ref: :  ## 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:  Default: nil (mysql will use image's default timezone, normally UTC)## Example: 'Australia/Sydney'# timezone:# Deployment AnnotationsdeploymentAnnotations: {}# To be added to the database server pod(s)podAnnotations: {}podLabels: {}## Set pod priorityClassName# priorityClassName: {}## Init container resources defaultsinitContainer:  resources:    requests:      memory: 10Mi      cpu: 10m[root@vms10 mysql]# 

注意:可以用vim编辑器搜索persistence。

关于values.yaml的其他部分,保持默认值即可,保存退出。

部署应用的语法为:

helm install <名字> <chart目录>

步骤6:在当前目录里执行安装操作。

##########实操验证##########[root@vms10 mysql]# helm install db .NAME: dbLAST DEPLOYED: Wed Sep 27 14:25:20 2023NAMESPACE: nshelmSTATUS: deployedREVISION: 1TEST SUITE: NoneNOTES:MySQL can be accessed via port 3306 on the following DNS name from within your cluster:db-mysql.nshelm.svc.cluster.localTo get your root password run:    MYSQL_ROOT_PASSWORD=$(kubectl get secret --namespace nshelm db-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 -il2. Install the mysql client:    $ apt-get update && apt-get install mysql-client -y3. Connect using the mysql cli, then provide your password:    $ mysql -h db-mysql -pTo 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/db-mysql 3306    mysql -h ${MYSQL_HOST} -P${MYSQL_PORT} -u root -p${MYSQL_ROOT_PASSWORD}[root@vms10 mysql]# 

步骤7:查看现在已经部署的release及pod。

##########实操验证##########[root@vms10 mysql]# helm lsNAME    NAMESPACE       REVISION        UPDATED                                 STATUS          CHART           APP VERSIONdb      nshelm          1               2023-09-27 14:25:20.142173048 +0800 CST deployed        mysql-1.6.8     5.7.30     [root@vms10 mysql]# [root@vms10 mysql]# kubectl get podsNAME                        READY   STATUS    RESTARTS   AGEdb-mysql-6f6474fdf4-qxmrz   1/1     Running   0          44s[root@vms10 mysql]# 

步骤8:安装mariadb客户端。

##########实操验证##########[root@vms10 mysql]# yum install mariadb -y Loaded plugins: fastestmirror, langpacksLoading mirror speeds from cached hostfileResolving Dependencies--> Running transaction check---> Package mariadb.x86_64 1:5.5.68-1.el7 will be installed--> Processing Dependency: mariadb-libs(x86-64) = 1:5.5.68-1.el7 for package: 1:mariadb-5.5.68-1.el7.x86_64--> Running transaction check---> Package mariadb-libs.x86_64 1:5.5.56-2.el7 will be updated---> Package mariadb-libs.x86_64 1:5.5.68-1.el7 will be an update--> Finished Dependency ResolutionDependencies Resolved========================================================================================================================================================================================================= Package                                            Arch                                         Version                                                Repository                                  Size=========================================================================================================================================================================================================Installing: mariadb                                            x86_64                                       1:5.5.68-1.el7                                         base                                       8.8 MUpdating for dependencies: mariadb-libs                                       x86_64                                       1:5.5.68-1.el7                                         base                                       760 kTransaction Summary=========================================================================================================================================================================================================Install  1 PackageUpgrade             ( 1 Dependent package)Total size: 9.5 MTotal download size: 8.8 MDownloading packages:mariadb-5.5.68-1.el7.x86_64.rpm                                                                                                                                                   | 8.8 MB  00:00:04     Running transaction checkRunning transaction testTransaction test succeededRunning transaction  Updating   : 1:mariadb-libs-5.5.68-1.el7.x86_64                                                                                                                                                    1/3   Installing : 1:mariadb-5.5.68-1.el7.x86_64                                                                                                                                                         2/3   Cleanup    : 1:mariadb-libs-5.5.56-2.el7.x86_64                                                                                                                                                    3/3   Verifying  : 1:mariadb-libs-5.5.68-1.el7.x86_64                                                                                                                                                    1/3   Verifying  : 1:mariadb-5.5.68-1.el7.x86_64                                                                                                                                                         2/3   Verifying  : 1:mariadb-libs-5.5.56-2.el7.x86_64                                                                                                                                                    3/3 Installed:  mariadb.x86_64 1:5.5.68-1.el7                                                                                                                                                                          Dependency Updated:  mariadb-libs.x86_64 1:5.5.68-1.el7                                                                                                                                                                     Complete![root@vms10 mysql]# 

步骤9:查看mysql pod的IP。

##########实操验证##########[root@vms10 mysql]# kubectl get pods -o wide --no-headers db-mysql-6f6474fdf4-qxmrz   1/1   Running   0     111s   10.244.81.107   vms11.rhce.cc   <none>   <none>[root@vms10 mysql]# 

步骤10:用mysql命令连接到此pod上。

##########实操验证##########[root@vms10 mysql]# mysql -uroot -predhat -h10.244.81.107Welcome to the MariaDB monitor.  Commands end with ; or \g.Your MySQL connection id is 26Server version: 5.7.18 MySQL Community Server (GPL)Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.MySQL [(none)]> quitBye[root@vms10 mysql]# 

步骤11:删除此release。

##########实操验证##########[root@vms10 mysql]# helm delete db release "db" uninstalled[root@vms10 mysql]# helm ls NAME    NAMESPACE       REVISION        UPDATED STATUS  CHART   APP VERSION[root@vms10 mysql]# [root@vms10 mysql]# cd[root@vms10 ~]# 

标签: #ubuntualternateiso