K8S用yaml资源清单部署mysql数据库,数据持久化保存

1.mysql数据库数据保存目录

[root@k8s-master ~]# mkdir -p /home/mysql/data

2.mysql的yaml清单

apiVersion: apps/v1
kind: Deployment 
metadata:
  name: mysql #名称,全局唯一
  namespace: default # 默认空间
spec:
  replicas: 1 #Pod 副本的期待数量
  selector:
    matchLabels:
      app: mysql # 符合目标的Pod拥有此标签
  template: # 根据此模版创建Pod的副本
    metadata:
      labels:
        app: mysql # Pod副本拥有的标签,对应Selector
    spec:
      #nodeName: k8s-master #指定K8S集群中的一个节点机器的名称,就是直接将pod调度到这台服务器上,用hostPath本机挂在卷挂在上,保证数据的安全性
      containers: # Pod的内容的定义部分
        - name: mysql # 容器的名称
          image: mysql:5.7 # 容器对应的Docker Image
          ports:
            - containerPort: 3306 # 容器应用监听的端口号
          env:
            - name: MYSQL_ROOT_PASSWORD # 设置mysql的初始化密码
              value: "123456" # 设置mysql的初始化密码
          volumeMounts:
          - mountPath: /var/lib/mysql #容器中的目录
            name: data-volume
      volumes:
      - name: data-volume
        hostPath:
        # 宿主机上目录位置
          path: /home/mysql/data
          type: DirectoryOrCreate
---
apiVersion: v1
kind: Service # 表明是Kubernetes Service
metadata:
  name: mysql # Service 的全局唯一名称
spec:
  selector:
    app: mysql
  type: NodePort
  ports: # Service 提供服务的端口
    - port: 3306 # Service 对应的Pod拥有这里定义的标签
      targetPort: 3306
      protocol: TCP
      nodePort: 30306 #这里指定了nodeport的端口,方式删除svc后重新分派端口,导致数据库无法登录
[root@k8s-master mysql]# ls
mysql.yaml
[root@k8s-master mysql]# kubectl apply -f mysql.yaml 
deployment.apps/mysql created
service/mysql created
[root@k8s-master mysql]# kubectl get pods,svc
NAME                          READY   STATUS    RESTARTS   AGE
pod/mysql-56f97f7bc4-n69ch    1/1     Running   0          6s

NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/kubernetes   ClusterIP   10.96.0.1        <none>        443/TCP          9d
service/mysql        NodePort    10.105.207.19    <none>        3306:30306/TCP   6s
[root@k8s-master mysql]# kubectl exec  -it pod/mysql-56f97f7bc4-n69ch -- sh #进入mysql容器
sh-4.2# mysql -uroot -p123456 #登录mysql
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 2
Server version: 5.7.40 MySQL Community Server (GPL)

Copyright (c) 2000, 2022, Oracle and/or its affiliates.

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> create DATABASE book;
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| book               |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.00 sec)

mysql> 

3.验证mysql登录

在这里插入图片描述在这里插入图片描述

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐