0


K8s集群中部署Mysql一主两从集群

主机规划

主机名IP地址角色操作系统硬件配置master10.62.158.200管理节点CentOS 72 Core/4G Memorynode0110.62.158.201工作节点01CentOS 72 Core/4G Memorynode0210.62.158.202工作节点02CentOS 72 Core/4G Memorynfs10.62.158.203文件共享节点CentOS 72 Core/4G Memory

设置主机名
[root@localhost ~]# hostnamectl set-hostname nfs[root@localhost ~]# ls
anaconda-ks.cfg  sysconfigure.sh
[root@localhost ~]# exit
登出

Connection closed by foreign host.

Disconnected from remote host(测试机 - 203) at 09:49:26.
安装NFS共享存储服务【服务端】

安装NFS软件包

[root@nfs ~]# yum install nfs-utils -y

创建NFS共享目录,该共享目录后续为多个服务提供共享文件夹

[root@nfs ~]# mkdir -p /data/nfs/{mysql-master,mysql-slaver-01,mysql-slaver-02}

修改NFS配置文件,指定共享目录是哪个

cat >> /etc/exports << EOF
/data/nfs/mysql-master 10.62.158.*(rw,sync,no_root_squash)/data/nfs/mysql-slaver-01 10.62.158.*(rw,sync,no_root_squash)/data/nfs/mysql-slaver-02 10.62.158.*(rw,sync,no_root_squash)
EOF
安装NFS共享存储服务【客户端】

k8s集群节点也需要安装

nfs-utils

用于访问NFS服务端(

nfs-utils

中不仅包含服务端程序,也包含客户端程序,不需要启动NFS程序,仅安装即可),否则无法访问NFS服务端

  • master & node01 & node02 节点安装客户端
[root@master ~]# yum install nfs-utils -y
[root@node01 ~]# yum install nfs-utils -y
[root@node02 ~]# yum install nfs-utils -y
  • master & node01 & node02 节点访问NFS服务端,查看共享信息,此时 master 节点 & node01节点 & node02节点 就可以使用共享目录进行文件的读写操作了
[root@master ~]# showmount -e 10.62.158.203
Export list for 10.62.158.203:
/data/nfs/mysql-slaver-02 10.62.158.*/data/nfs/mysql-slaver-01 10.62.158.*/data/nfs/mysql-master    10.62.158.*
[root@node01 ~]# showmount -e 10.62.158.203
Export list for 10.62.158.203:
/data/nfs/mysql-slaver-02 10.62.158.*/data/nfs/mysql-slaver-01 10.62.158.*/data/nfs/mysql-master    10.62.158.*
[root@node02 ~]# showmount -e 10.62.158.203
Export list for 10.62.158.203:
/data/nfs/mysql-slaver-02 10.62.158.*/data/nfs/mysql-slaver-01 10.62.158.*/data/nfs/mysql-master    10.62.158.*
前置工作

创建命名空间

[root@master ~]# kubectl create namespace deploy-mysql  
namespace/deploy-mysql created
[root@master ~]# kubectl get ns
NAME              STATUS   AGE
default           Active   6d21h
deploy-mysql      Active   13s
kube-node-lease   Active   6d21h
kube-public       Active   6d21h
kube-system       Active   6d21h

创建MySQL密码的Secret

[root@master ~]# kubectl create secret generic mysql-password --namespace=deploy-mysql --from-literal=mysql_root_password=root --dry-run=client -o=yaml
apiVersion: v1
data:
  mysql_root_password: cm9vdA==
kind: Secret
metadata:
  creationTimestamp: null
  name: mysql-password
  namespace: deploy-mysql

复制保存生成后的内容为 mysql-secret.yaml 文件

[root@master ~]# vim mysql-secret.yaml
apiVersion: v1
data:
  mysql_root_password: cm9vdA==
kind: Secret
metadata:
  creationTimestamp: null
  name: mysql-password
  namespace: deploy-mysql

创建Secret

[root@master ~]# kubectl apply -f mysql-secret.yaml 
secret/mysql-password created

列出命名空间 deploy-mysql 中的所有 Secrets

[root@master ~]# kubectl get secret -n deploy-mysql
NAME                  TYPEDATA   AGE
default-token-272c8   kubernetes.io/service-account-token   3      8m51s
mysql-password        Opaque                                1      25s
搭建部署mysql主节点

创建持久卷(PV)和持久卷声明(PVC)

[root@master ~]# vim mysql-master-pv-pvc.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: deploy-mysql-master-nfs-pv  # PV 的名称
  namespace: deploy-mysql  # PV 所属的命名空间
spec:
  capacity:
    storage: 1Gi  # PV 的存储容量为 1GB(根据实际调整)
  accessModes:
    - ReadWriteMany  # 允许多个 Pod 同时对 PV 进行读写访问
  nfs:
    server: 10.62.158.203  # NFS 服务器的 IP 地址
    path: /data/nfs/mysql-master  # NFS 服务器上暴露的目录路径
  storageClassName: "nfs"# PV 使用的存储类名称为 "nfs"---

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: deploy-mysql-master-nfs-pvc  # PVC 的名称
  namespace: deploy-mysql  # PVC 所属的命名空间
spec:
  accessModes:
    - ReadWriteMany  # PVC 的访问模式为 ReadWriteMany
  storageClassName: "nfs"# PVC 使用的存储类名称为 "nfs"
  resources:
    requests:
      storage: 1Gi  # 请求 1GB 的存储空间
  volumeName: deploy-mysql-master-nfs-pv  # 将 PVC 绑定到 PV 的名称为 "deploy-mysql-master-nfs-pv"

创建 PV 和 PVC

[root@master ~]# kubectl apply -f mysql-master-pv-pvc.yaml
persistentvolume/deploy-mysql-master-nfs-pv created
persistentvolumeclaim/deploy-mysql-master-nfs-pvc created

查看PV 和 PVC

[root@master ~]# kubectl get pv,pvc -n deploy-mysql
NAME                                          CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                                      STORAGECLASS   REASON   AGE
persistentvolume/deploy-mysql-master-nfs-pv   5Gi        RWX            Retain           Bound    deploy-mysql/deploy-mysql-master-nfs-pvc   nfs                     46s

NAME                                                STATUS   VOLUME                       CAPACITY   ACCESS MODES   STORAGECLASS   AGE
persistentvolumeclaim/deploy-mysql-master-nfs-pvc   Bound    deploy-mysql-master-nfs-pv   5Gi        RWX            nfs            46s

创建主节点的mysql配置文件,同步的数据库为:db_k8s

[root@master ~]# vi my.cnf
[mysqld]skip-host-cache                                 # 不使用主机缓存skip-name-resolve                               # 不解析主机名
datadir          = /var/lib/mysql               # 数据文件存放目录
socket           = /var/run/mysqld/mysqld.sock  # MySQL服务器套接字文件路径
secure-file-priv = /var/lib/mysql-files         # 指定安全文件的位置
pid-file         = /var/run/mysqld/mysqld.pid   # PID文件路径
user             = mysql                        # MySQL服务运行的用户
secure-file-priv = NULL                         # 禁用安全文件访问限制
server-id        = 1                            # 服务器唯一标识符
log-bin          = master-bin                   # 启用二进制日志,并指定日志文件名
log_bin_index    = master-bin.index             # 二进制日志索引文件路径
binlog_do_db     = db_k8s                       # 仅记录指定数据库的操作到二进制日志
binlog_ignore_db = information_schema           # 忽略记录指定数据库的操作到二进制日志
binlog_ignore_db = mysql                        # 忽略记录指定数据库的操作到二进制日志
binlog_ignore_db = performance_schema           # 忽略记录指定数据库的操作到二进制日志
binlog_ignore_db = sys                          # 忽略记录指定数据库的操作到二进制日志
binlog-format    = ROW                          # 设置二进制日志格式为行格式[client]
socket           = /var/run/mysqld/mysqld.sock  # 客户端连接MySQL服务器时使用的套接字文件路径!includedir /etc/mysql/conf.d/                  # 包含额外的配置文件目录

生成 master 节点的mysql ConfigMap 的 YAML 资源描述文件,指定mysql 配置文件 my.cnf

[root@master ~]# kubectl create configmap mysql-master-configmap -n deploy-mysql --from-file=my.cnf=my.cnf --dry-run=client -o yaml
apiVersion: v1
data:
  my.cnf: |[mysqld]skip-host-cache                                 # 不使用主机缓存skip-name-resolve                               # 不解析主机名
    datadir          = /var/lib/mysql               # 数据文件存放目录
    socket           = /var/run/mysqld/mysqld.sock  # MySQL服务器套接字文件路径
    secure-file-priv = /var/lib/mysql-files         # 指定安全文件的位置
    pid-file         = /var/run/mysqld/mysqld.pid   # PID文件路径
    user             = mysql                        # MySQL服务运行的用户
    secure-file-priv = NULL                         # 禁用安全文件访问限制
    server-id        = 1                            # 服务器唯一标识符
    log-bin          = master-bin                   # 启用二进制日志,并指定日志文件名
    log_bin_index    = master-bin.index             # 二进制日志索引文件路径
    binlog_do_db     = db_k8s                       # 仅记录指定数据库的操作到二进制日志
    binlog_ignore_db = information_schema           # 忽略记录指定数据库的操作到二进制日志
    binlog_ignore_db = mysql                        # 忽略记录指定数据库的操作到二进制日志
    binlog_ignore_db = performance_schema           # 忽略记录指定数据库的操作到二进制日志
    binlog_ignore_db = sys                          # 忽略记录指定数据库的操作到二进制日志
    binlog-format    = ROW                          # 设置二进制日志格式为行格式[client]
    socket           = /var/run/mysqld/mysqld.sock  # 客户端连接MySQL服务器时使用的套接字文件路径!includedir /etc/mysql/conf.d/                  # 包含额外的配置文件目录
kind: ConfigMap
metadata:
  creationTimestamp: null
  name: mysql-master-configmap
  namespace: deploy-mysql

查看当前命名空间中的configmap

[root@master ~]# kubectl get configmaps -n deploy-mysql
NAME                       DATA   AGE
kube-root-ca.crt           1      140m
mysql-master-configmap     1      97m

复制保存生成后的内容为文件 mysql-master-configmap.yaml,并额外添加svc、StatefulSet的配置

[root@master ~]# vim mysql-master-configmap.yaml
apiVersion: v1
data:
  my.cnf: |+[mysqld]skip-host-cache                             # 不使用主机缓存skip-name-resolve                           # 不解析主机名
    datadir          = /var/lib/mysql           # 数据文件存放目录
    socket           = /var/run/mysqld/mysqld.sock  # MySQL服务器套接字文件路径
    secure-file-priv = /var/lib/mysql-files     # 指定安全文件的位置
    pid-file         = /var/run/mysqld/mysqld.pid   # PID文件路径
    user             = mysql                    # MySQL服务运行的用户
    secure-file-priv = NULL                     # 禁用安全文件访问限制
    server-id        = 1                        # 服务器唯一标识符
    log-bin          = master-bin               # 启用二进制日志,并指定日志文件名
    binlog_do_db     = db_k8s                   # 仅记录指定数据库的操作到二进制日志
    log_bin_index    = master-bin.index         # 二进制日志索引文件路径
    binlog_ignore_db = information_schema       # 忽略记录指定数据库的操作到二进制日志
    binlog_ignore_db = mysql                    # 忽略记录指定数据库的操作到二进制日志
    binlog_ignore_db = performance_schema       # 忽略记录指定数据库的操作到二进制日志
    binlog_ignore_db = sys                      # 忽略记录指定数据库的操作到二进制日志
    binlog-format    = ROW                      # 设置二进制日志格式为行格式[client]
    socket           = /var/run/mysqld/mysqld.sock  # 客户端连接MySQL服务器时使用的套接字文件路径

kind: ConfigMap
metadata:
  creationTimestamp: null
  name: mysql-master-configmap
  namespace: deploy-mysql

---

apiVersion: v1
kind: Service
metadata:
  name: deploy-mysql-master-svc  # 定义服务的名称
  namespace: deploy-mysql  # 定义服务所属的命名空间
  labels:
    app: mysql-master
spec:
  ports:
  - port: 3306  # 服务暴露的端口号
    name: mysql
    targetPort: 3306
    nodePort: 30306  # NodePort 类型服务的端口
  selector:
    app: mysql-master  # 选择器,选择哪些 Pod 作为后端type: NodePort  # 服务类型为 NodePort
  sessionAffinity: ClientIP  # 会话亲和性设置为 ClientIP---

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: deploy-mysql-master  # StatefulSet 的名称
  namespace: deploy-mysql  # StatefulSet 所属的命名空间
spec:
  selector:
    matchLabels:
      app: mysql-master  # 选择器,用于选择管理的 Pod
  serviceName: "deploy-mysql-master-svc"# 关联的 Service 的名称
  replicas: 1  # 副本数
  template:
    metadata:
      labels:
        app: mysql-master  # Pod 模板的标签
    spec:
      terminationGracePeriodSeconds: 10  # 终止优雅期的秒数
      containers:
      - args:
        ---character-set-server=utf8mb4  # MySQL 参数设置---collation-server=utf8mb4_unicode_ci
        ---lower_case_table_names=1
        ---default-time_zone=+8:00
        name: mysql  # 容器的名称
        image: mysql:8.0.34  # 容器镜像
        ports:
        - containerPort: 3306  # 容器监听的端口号
          name: mysql
        volumeMounts:
        - name: mysql-data# 挂载的持久化卷
          mountPath: /var/lib/mysql
        - name: mysql-conf  # 挂载的 ConfigMap
          mountPath: /etc/my.cnf
          readOnly: true
          subPath: my.cnf
        env:  # 容器的环境变量- name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              key: mysql_root_password
              name: mysql-password  # 引用的 Secret 的名称
      volumes:
      - name: mysql-data# 持久化卷的名称
        persistentVolumeClaim:
          claimName: deploy-mysql-master-nfs-pvc  # 持久化卷声明的名称- name: mysql-conf  # ConfigMap 的名称
        configMap:
          name: mysql-master-configmap  # ConfigMap 的名称
          items:
          - key: my.cnf  # ConfigMap 中的键值对
            mode: 0644  # 文件权限
            path: my.cnf  # 挂载路径

应用 YAML 文件到 Kubernetes 集群

[root@master ~]# kubectl apply -f mysql-master-configmap.yaml
configmap/mysql-master-configmap created
service/deploy-mysql-master-svc created
statefulset.apps/deploy-mysql-master created

获取在指定命名空间[ deploy-mysq ]中所有资源的详细信息

[root@master ~]# kubectl get all -o wide -n deploy-mysql
NAME                        READY   STATUS    RESTARTS   AGE    IP                NODE     NOMINATED NODE   READINESS GATES
pod/deploy-mysql-master-0   1/1     Running   0          100s   192.168.196.131   node01   <none>           <none>

NAME                              TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE    SELECTOR
service/deploy-mysql-master-svc   NodePort   10.109.63.216   <none>        3306:30306/TCP   100s   app=mysql-master

NAME                                   READY   AGE    CONTAINERS   IMAGES
statefulset.apps/deploy-mysql-master   1/1     100s   mysql        mysql:8.0.34

查看Pod日志

[root@master ~]# kubectl logs deploy-mysql-master-0 -n deploy-mysql

查看 NFS 服务器中的共享目录,检查其中的文件并确认是否存在 log-bin 文件:master-bin

[root@nfs nfs]# ls -l /data/nfs/mysql-master/
总用量 96720
-rw-r----- 1 polkitd input       56 4月  19 10:54 auto.cnf
-rw------- 1 polkitd input     1676 4月  19 10:55 ca-key.pem
-rw-r--r-- 1 polkitd input     1112 4月  19 10:55 ca.pem
-rw-r--r-- 1 polkitd input     1112 4月  19 10:55 client-cert.pem
-rw------- 1 polkitd input     1680 4月  19 10:55 client-key.pem
-rw-r----- 1 polkitd input   196608 4月  19 11:11 #ib_16384_0.dblwr-rw-r----- 1 polkitd input  8585216 4月  19 10:55 #ib_16384_1.dblwr-rw-r----- 1 polkitd input     3541 4月  19 11:07 ib_buffer_pool
-rw-r----- 1 polkitd input 12582912 4月  19 11:09 ibdata1
-rw-r----- 1 polkitd input 12582912 4月  19 11:10 ibtmp1
drwxr-x--- 2 polkitd input     4096 4月  19 11:09 #innodb_redo
drwxr-x--- 2 polkitd input      187 4月  19 11:09 #innodb_temp-rw-r----- 1 polkitd input      180 4月  19 10:55 master-bin.000001
-rw-r----- 1 polkitd input      180 4月  19 10:55 master-bin.000002
-rw-r----- 1 polkitd input      180 4月  19 10:59 master-bin.000003
-rw-r----- 1 polkitd input      180 4月  19 11:07 master-bin.000004
-rw-r----- 1 polkitd input      157 4月  19 11:09 master-bin.000005
-rw-r----- 1 polkitd input      100 4月  19 11:09 master-bin.index
drwxr-x--- 2 polkitd input      143 4月  19 10:55 mysql
-rw-r----- 1 polkitd input 31457280 4月  19 11:09 mysql.ibd
lrwxrwxrwx 1 polkitd input       27 4月  19 11:09 mysql.sock -> /var/run/mysqld/mysqld.sock
drwxr-x--- 2 polkitd input     8192 4月  19 10:55 performance_schema
-rw------- 1 polkitd input     1676 4月  19 10:55 private_key.pem
-rw-r--r-- 1 polkitd input      452 4月  19 10:55 public_key.pem
-rw-r--r-- 1 polkitd input     1112 4月  19 10:55 server-cert.pem
-rw------- 1 polkitd input     1680 4月  19 10:55 server-key.pem
drwxr-x--- 2 polkitd input       28 4月  19 10:55 sys
-rw-r----- 1 polkitd input 16777216 4月  19 11:11 undo_001
-rw-r----- 1 polkitd input 16777216 4月  19 11:11 undo_002
搭建部署mysql主节点slave01

创建持久卷(PV)和持久卷声明(PVC)

[root@master ~]# vim mysql-slave01-pv-pvc.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: deploy-mysql-slave01-nfs-pv  # PV 的名称
  namespace: deploy-mysql  # PV 所属的命名空间
spec:
  capacity:
    storage: 1Gi  # PV 的存储容量为 1GB(根据实际调整)
  accessModes:
    - ReadWriteMany  # 允许多个 Pod 同时对 PV 进行读写访问
  nfs:
    server: 10.62.158.203  # NFS 服务器的 IP 地址
    path: /data/nfs/mysql-slaver-01  # NFS 服务器上暴露的目录路径
  storageClassName: "nfs"# PV 使用的存储类名称为 "nfs"---

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: deploy-mysql-slave01-nfs-pvc  # PVC 的名称
  namespace: deploy-mysql  # PVC 所属的命名空间
spec:
  accessModes:
    - ReadWriteMany  # PVC 的访问模式为 ReadWriteMany
  storageClassName: "nfs"# PVC 使用的存储类名称为 "nfs"
  resources:
    requests:
      storage: 1Gi  # 请求 1GB 的存储空间
  volumeName: deploy-mysql-slave01-nfs-pv  # 将 PVC 绑定到 PV 的名称为 "deploy-mysql-master-nfs-pv"

创建 PV 和 PVC

[root@master ~]# kubectl apply -f mysql-slave01-pv-pvc.yaml
persistentvolume/deploy-mysql-slave01-nfs-pv created
persistentvolumeclaim/deploy-mysql-slave01-nfs-pvc created

查看PV 和 PVC

[root@master ~]# kubectl get pv,pvc -n deploy-mysql
NAME                                           CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                                       STORAGECLASS   REASON   AGE
persistentvolume/deploy-mysql-master-nfs-pv    5Gi        RWX            Retain           Bound    deploy-mysql/deploy-mysql-master-nfs-pvc    nfs                     114m
persistentvolume/deploy-mysql-slave01-nfs-pv   1Gi        RWX            Retain           Bound    deploy-mysql/deploy-mysql-slave01-nfs-pvc   nfs                     27s

NAME                                                 STATUS   VOLUME                        CAPACITY   ACCESS MODES   STORAGECLASS   AGE
persistentvolumeclaim/deploy-mysql-master-nfs-pvc    Bound    deploy-mysql-master-nfs-pv    5Gi        RWX            nfs            114m
persistentvolumeclaim/deploy-mysql-slave01-nfs-pvc   Bound    deploy-mysql-slave01-nfs-pv   1Gi        RWX            nfs            27s

创建 salve01 从节点的 mysql 配置文件

[root@master ~]# vim my.cnf
[mysqld]skip-host-cache  # 不使用主机缓存skip-name-resolve  # 不进行主机名解析
datadir          = /var/lib/mysql  # MySQL 数据目录
socket           = /var/run/mysqld/mysqld.sock  # MySQL Socket 文件路径
secure-file-priv = /var/lib/mysql-files  # 安全文件目录
pid-file         = /var/run/mysqld/mysqld.pid  # MySQL 进程 ID 文件路径
user             = mysql  # MySQL 运行用户
secure-file-priv = NULL  # 安全文件权限设置
server-id        = 2  # 从节点服务器 ID
log-bin          = slave-bin  # 二进制日志文件名
relay-log        = slave-relay-bin  # 中继日志文件名
relay-log-index  = slave-relay-bin.index  # 中继日志索引文件名[client]
socket           = /var/run/mysqld/mysqld.sock  # MySQL 客户端 Socket 文件路径

生成 slave01 节点的 mysql ConfigMap 的 YAML 资源描述文件

[root@master ~]# kubectl create configmap mysql-slave01-configmap -n deploy-mysql --from-file=my.cnf --dry-run=client -o yaml
apiVersion: v1
data:
  my.cnf: |[mysqld]skip-host-cache  # 不使用主机缓存skip-name-resolve  # 不进行主机名解析
    datadir          = /var/lib/mysql  # MySQL 数据目录
    socket           = /var/run/mysqld/mysqld.sock  # MySQL Socket 文件路径
    secure-file-priv = /var/lib/mysql-files  # 安全文件目录
    pid-file         = /var/run/mysqld/mysqld.pid  # MySQL 进程 ID 文件路径
    user             = mysql  # MySQL 运行用户
    secure-file-priv = NULL  # 安全文件权限设置
    server-id        = 2  # 从节点服务器 ID
    log-bin          = slave-bin  # 二进制日志文件名
    relay-log        = slave-relay-bin  # 中继日志文件名
    relay-log-index  = slave-relay-bin.index  # 中继日志索引文件名[client]
    socket           = /var/run/mysqld/mysqld.sock  # MySQL 客户端 Socket 文件路径
kind: ConfigMap
metadata:
  creationTimestamp: null
  name: mysql-slave01-configmap
  namespace: deploy-mysql

复制保存生成后的内容为文件 mysql-slave01-configmap.yaml,添加svc、StatefulSet的配置

[root@master ~]# vim mysql-slave01-configmap.yaml
apiVersion: v1
data:
  my.cnf: |[mysqld]skip-host-cache  # 不使用主机缓存skip-name-resolve  # 不进行主机名解析
    datadir          = /var/lib/mysql  # MySQL 数据目录
    socket           = /var/run/mysqld/mysqld.sock  # MySQL Socket 文件路径
    secure-file-priv = /var/lib/mysql-files  # 安全文件目录
    pid-file         = /var/run/mysqld/mysqld.pid  # MySQL 进程 ID 文件路径
    user             = mysql  # MySQL 运行用户
    secure-file-priv = NULL  # 安全文件权限设置
    server-id        = 2  # 从节点服务器 ID
    log-bin          = slave-bin  # 二进制日志文件名
    relay-log        = slave-relay-bin  # 中继日志文件名
    relay-log-index  = slave-relay-bin.index  # 中继日志索引文件名[client]
    socket           = /var/run/mysqld/mysqld.sock  # MySQL 客户端 Socket 文件路径
kind: ConfigMap
metadata:
  creationTimestamp: null
  name: mysql-slave01-configmap
  namespace: deploy-mysql

---

apiVersion: v1
kind: Service
metadata:
  name: deploy-mysql-slave-svc  # MySQL从节点服务名称
  namespace: deploy-mysql  # 部署的命名空间
  labels:
    app: mysql-slave
spec:
  ports:
  - port: 3306
    name: mysql
    targetPort: 3306
    nodePort: 30308  # 暴露的节点端口
  selector:
    app: mysql-slave
  type: NodePort
  sessionAffinity: ClientIP

---

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: deploy-mysql-slave-01  # MySQL从节点StatefulSet名称
  namespace: deploy-mysql  # 部署的命名空间
spec:
  selector:
    matchLabels:
      app: mysql-slave-01
  serviceName: "deploy-mysql-slave-svc"# 关联的Service名称
  replicas: 1
  template:
    metadata:
      labels:
        app: mysql-slave-01
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - args:
        ---character-set-server=utf8mb4
        ---collation-server=utf8mb4_unicode_ci
        ---lower_case_table_names=1
        ---default-time_zone=+8:00
        name: mysql
        # image: docker.io/library/mysql:8.0.34
        image: mysql:8.0.34  # MySQL镜像地址
        ports:
        - containerPort: 3306
          name: mysql
        volumeMounts:
        - name: mysql-data
          mountPath: /var/lib/mysql
        - name: mysql-conf
          mountPath: /etc/my.cnf
          readOnly: true
          subPath: my.cnf
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              key: mysql_root_password
              name: mysql-password
      volumes:
      - name: mysql-data
        persistentVolumeClaim:
          claimName: deploy-mysql-slave01-nfs-pvc  # 持久卷声明名称- name: mysql-conf
        configMap:
          name: mysql-slave01-configmap # ConfigMap名称
          items:
          - key: my.cnf
            mode: 0644
            path: my.cnf

应用 YAML 文件到 Kubernetes 集群

[root@master ~]# kubectl apply -f mysql-slave01-configmap.yaml
configmap/mysql-slave01-configmap created
service/deploy-mysql-slave-svc created
statefulset.apps/deploy-mysql-slave-01 created

获取在指定命名空间(deploy-mysql)中所有资源的详细信息

[root@master ~]# kubectl get all -o wide -n deploy-mysql
NAME                          READY   STATUS    RESTARTS   AGE    IP                NODE     NOMINATED NODE   READINESS GATES
pod/deploy-mysql-master-0     1/1     Running   0          138m   192.168.196.133   node01   <none>           <none>
pod/deploy-mysql-slave-01-0   1/1     Running   0          6s     192.168.196.134   node01   <none>           <none>

NAME                              TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE    SELECTOR
service/deploy-mysql-master-svc   NodePort   10.109.46.105   <none>        3306:30306/TCP   138m   app=mysql-master
service/deploy-mysql-slave-svc    NodePort   10.99.187.187   <none>        3306:30308/TCP   6s     app=mysql-slave

NAME                                     READY   AGE    CONTAINERS   IMAGES
statefulset.apps/deploy-mysql-master     1/1     138m   mysql        mysql:8.0.34
statefulset.apps/deploy-mysql-slave-01   1/1     6s     mysql        mysql:8.0.34
搭建部署mysql主节点slave02

创建持久卷(PV)和持久卷声明(PVC)

[root@master ~]# vim mysql-slave02-pv-pvc.yaml
apiVersion: v1
kind: PersistentVolume
metadata:
  name: deploy-mysql-slave02-nfs-pv  # PV 的名称
  namespace: deploy-mysql  # PV 所属的命名空间
spec:
  capacity:
    storage: 1Gi  # PV 的存储容量为 1GB(根据实际调整)
  accessModes:
    - ReadWriteMany  # 允许多个 Pod 同时对 PV 进行读写访问
  nfs:
    server: 10.62.158.203  # NFS 服务器的 IP 地址
    path: /data/nfs/mysql-slaver-02  # NFS 服务器上暴露的目录路径
  storageClassName: "nfs"# PV 使用的存储类名称为 "nfs"---

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: deploy-mysql-slave02-nfs-pvc  # PVC 的名称
  namespace: deploy-mysql  # PVC 所属的命名空间
spec:
  accessModes:
    - ReadWriteMany  # PVC 的访问模式为 ReadWriteMany
  storageClassName: "nfs"# PVC 使用的存储类名称为 "nfs"
  resources:
    requests:
      storage: 1Gi  # 请求 1GB 的存储空间
  volumeName: deploy-mysql-slave02-nfs-pv  # 将 PVC 绑定到 PV 的名称为 "deploy-mysql-master-nfs-pv"

创建 PV 和 PVC

[root@master ~]# kubectl apply -f mysql-slave02-pv-pvc.yaml
persistentvolume/deploy-mysql-slave02-nfs-pv created
persistentvolumeclaim/deploy-mysql-slave02-nfs-pvc created

查看PV 和 PVC

[root@master ~]# kubectl get pv,pvc -n deploy-mysql
NAME                                           CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                                       STORAGECLASS   REASON   AGE
persistentvolume/deploy-mysql-master-nfs-pv    5Gi        RWX            Retain           Bound    deploy-mysql/deploy-mysql-master-nfs-pvc    nfs                     147m
persistentvolume/deploy-mysql-slave01-nfs-pv   1Gi        RWX            Retain           Bound    deploy-mysql/deploy-mysql-slave01-nfs-pvc   nfs                     33m
persistentvolume/deploy-mysql-slave02-nfs-pv   1Gi        RWX            Retain           Bound    deploy-mysql/deploy-mysql-slave02-nfs-pvc   nfs                     25s

NAME                                                 STATUS   VOLUME                        CAPACITY   ACCESS MODES   STORAGECLASS   AGE
persistentvolumeclaim/deploy-mysql-master-nfs-pvc    Bound    deploy-mysql-master-nfs-pv    5Gi        RWX            nfs            147m
persistentvolumeclaim/deploy-mysql-slave01-nfs-pvc   Bound    deploy-mysql-slave01-nfs-pv   1Gi        RWX            nfs            33m
persistentvolumeclaim/deploy-mysql-slave02-nfs-pvc   Bound    deploy-mysql-slave02-nfs-pv   1Gi        RWX            nfs            25s

创建 salve02 从节点的 mysql 配置文件

[root@master ~]# vim my.cnf
[mysqld]skip-host-cache  # 不使用主机缓存skip-name-resolve  # 不进行主机名解析
datadir          = /var/lib/mysql  # MySQL 数据目录
socket           = /var/run/mysqld/mysqld.sock  # MySQL Socket 文件路径
secure-file-priv = /var/lib/mysql-files  # 安全文件目录
pid-file         = /var/run/mysqld/mysqld.pid  # MySQL 进程 ID 文件路径
user             = mysql  # MySQL 运行用户
secure-file-priv = NULL  # 安全文件权限设置
server-id        = 3  # 从节点服务器 ID
log-bin          = slave-bin  # 二进制日志文件名
relay-log        = slave-relay-bin  # 中继日志文件名
relay-log-index  = slave-relay-bin.index  # 中继日志索引文件名[client]
socket           = /var/run/mysqld/mysqld.sock  # MySQL 客户端 Socket 文件路径

生成 slave02 节点的 mysql ConfigMap 的 YAML 资源描述文件

[root@master ~]# kubectl create configmap mysql-slave02-configmap -n deploy-mysql --from-file=my.cnf --dry-run=client -o yaml
apiVersion: v1
data:
  my.cnf: |[mysqld]skip-host-cache  # 不使用主机缓存skip-name-resolve  # 不进行主机名解析
    datadir          = /var/lib/mysql  # MySQL 数据目录
    socket           = /var/run/mysqld/mysqld.sock  # MySQL Socket 文件路径
    secure-file-priv = /var/lib/mysql-files  # 安全文件目录
    pid-file         = /var/run/mysqld/mysqld.pid  # MySQL 进程 ID 文件路径
    user             = mysql  # MySQL 运行用户
    secure-file-priv = NULL  # 安全文件权限设置
    server-id        = 3  # 从节点服务器 ID
    log-bin          = slave-bin  # 二进制日志文件名
    relay-log        = slave-relay-bin  # 中继日志文件名
    relay-log-index  = slave-relay-bin.index  # 中继日志索引文件名[client]
    socket           = /var/run/mysqld/mysqld.sock  # MySQL 客户端 Socket 文件路径
kind: ConfigMap
metadata:
  creationTimestamp: null
  name: mysql-slave02-configmap
  namespace: deploy-mysql

复制保存生成后的内容为文件 mysql-slave02-configmap.yaml,添加svc、StatefulSet的配置

[root@master ~]# vim mysql-slave02-configmap.yaml
apiVersion: v1
data:
  my.cnf: |[mysqld]skip-host-cache  # 不使用主机缓存skip-name-resolve  # 不进行主机名解析
    datadir          = /var/lib/mysql  # MySQL 数据目录
    socket           = /var/run/mysqld/mysqld.sock  # MySQL Socket 文件路径
    secure-file-priv = /var/lib/mysql-files  # 安全文件目录
    pid-file         = /var/run/mysqld/mysqld.pid  # MySQL 进程 ID 文件路径
    user             = mysql  # MySQL 运行用户
    secure-file-priv = NULL  # 安全文件权限设置
    server-id        = 3  # 从节点服务器 ID
    log-bin          = slave-bin  # 二进制日志文件名
    relay-log        = slave-relay-bin  # 中继日志文件名
    relay-log-index  = slave-relay-bin.index  # 中继日志索引文件名[client]
    socket           = /var/run/mysqld/mysqld.sock  # MySQL 客户端 Socket 文件路径
kind: ConfigMap
metadata:
  creationTimestamp: null
  name: mysql-slave02-configmap
  namespace: deploy-mysql

---

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: deploy-mysql-slave-02  # MySQL从节点StatefulSet名称
  namespace: deploy-mysql  # 部署的命名空间
spec:
  selector:
    matchLabels:
      app: mysql-slave-02
  serviceName: "deploy-mysql-slave-svc"# 关联的Service名称
  replicas: 1
  template:
    metadata:
      labels:
        app: mysql-slave-02
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - args:
        ---character-set-server=utf8mb4
        ---collation-server=utf8mb4_unicode_ci
        ---lower_case_table_names=1
        ---default-time_zone=+8:00
        name: mysql
        # image: docker.io/library/mysql:8.0.34
        image: mysql:8.0.34  # MySQL镜像地址
        ports:
        - containerPort: 3306
          name: mysql
        volumeMounts:
        - name: mysql-data
          mountPath: /var/lib/mysql
        - name: mysql-conf
          mountPath: /etc/my.cnf
          readOnly: true
          subPath: my.cnf
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              key: mysql_root_password
              name: mysql-password
      volumes:
      - name: mysql-data
        persistentVolumeClaim:
          claimName: deploy-mysql-slave02-nfs-pvc  # 持久卷声明名称- name: mysql-conf
        configMap:
          name: mysql-slave02-configmap # ConfigMap名称
          items:
          - key: my.cnf
            mode: 0644
            path: my.cnf

应用 YAML 文件到 Kubernetes 集群

[root@master ~]# kubectl apply -f mysql-slave02-configmap.yaml
configmap/mysql-slave02-configmap created
statefulset.apps/deploy-mysql-slave-02 created

获取在指定命名空间(deploy-mysql)中所有资源的详细信息

[root@master ~]# kubectl get all -o wide -n deploy-mysql
NAME                          READY   STATUS    RESTARTS   AGE    IP                NODE     NOMINATED NODE   READINESS GATES
pod/deploy-mysql-master-0     1/1     Running   0          165m   192.168.196.133   node01   <none>           <none>
pod/deploy-mysql-slave-01-0   1/1     Running   0          27m    192.168.196.134   node01   <none>           <none>
pod/deploy-mysql-slave-02-0   1/1     Running   0          9s     192.168.196.135   node01   <none>           <none>

NAME                              TYPE       CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE    SELECTOR
service/deploy-mysql-master-svc   NodePort   10.109.46.105   <none>        3306:30306/TCP   165m   app=mysql-master
service/deploy-mysql-slave-svc    NodePort   10.99.187.187   <none>        3306:30308/TCP   27m    app=mysql-slave

NAME                                     READY   AGE    CONTAINERS   IMAGES
statefulset.apps/deploy-mysql-master     1/1     165m   mysql        mysql:8.0.34
statefulset.apps/deploy-mysql-slave-01   1/1     27m    mysql        mysql:8.0.34
statefulset.apps/deploy-mysql-slave-02   1/1     9s     mysql        mysql:8.0.34
使三台服务器组成一个集群

启动一个交互式会话,连接到名为 deploy-mysql-master-0 的 Pod,查看主节点的状态

[root@master ~]# kubectl exec -it -n deploy-mysql deploy-mysql-master-0 -- mysql -uroot -p
Enter password: 

查看主节点的状态

mysql> show master status;+-------------------+----------+--------------+-------------------------------------------------+-------------------+| File              | Position | Binlog_Do_DB | Binlog_Ignore_DB                                | Executed_Gtid_Set |+-------------------+----------+--------------+-------------------------------------------------+-------------------+| master-bin.000005 |      157 | db_k8s       | information_schema,mysql,performance_schema,sys ||+-------------------+----------+--------------+-------------------------------------------------+-------------------+
1 row in set(0.00 sec)

配置从节点(Slave)连接到主节点(Master)

  • 进入从节点mysql pod内部,执行以下命令加入集群中
CHANGE MASTER TO 
    MASTER_HOST='deploy-mysql-master-0.deploy-mysql-master-svc.deploy-mysql.svc.cluster.local', 
    MASTER_PORT=3306, 
    MASTER_USER='root', 
    MASTER_PASSWORD='root', 
    MASTER_LOG_FILE='master-bin.000003', 
    MASTER_LOG_POS=157, 
    MASTER_CONNECT_RETRY=30, 
    GET_MASTER_PUBLIC_KEY=1;
  • 需要注意下面的几个参数:
master_host: 这个参数是master的地址,kubernetes提供的解析规则是 pod名称.service名称.命名空间.svc.cluster.local ,所以我们master的mysql地址是 deploy-mysql-master-0.deploy-mysql-master-svc.deploy-mysql.svc.cluster.local
master_port: 主节点的mysql端口,我们没改默认是3306
master_user: 登录到主节点的mysql用户
master_password: 登录到主节点要用到的密码
master_log_file: 我们之前查看mysql主节点状态时候的 File 字段
master_log_pos: 我们之前查看mysql主节点状态时候的 Position 字段
master_connect_retry: 主节点重连时间
get_master_public_key: 连接主mysql的公钥获取方式
slave01 加入master

进入deploy-mysql-slave-01-0 的 Pod,密码root

[root@master ~]# kubectl exec -itn deploy-mysql pod/deploy-mysql-slave-01-0 -- mysql -uroot -p

配置从节点(Slave)连接到主节点(Master)的参数,执行以下命令来配置它们连接到主节点

CHANGE MASTER TO 
    MASTER_HOST='deploy-mysql-master-0.deploy-mysql-master-svc.deploy-mysql.svc.cluster.local', 
    MASTER_PORT=3306, 
    MASTER_USER='root', 
    MASTER_PASSWORD='root', 
    MASTER_LOG_FILE='master-bin.000005', 
    MASTER_LOG_POS=157, 
    MASTER_CONNECT_RETRY=30, 
    GET_MASTER_PUBLIC_KEY=1;

在这里插入图片描述
启动从节点的复制进程

mysql>start slave;
Query OK,0rows affected,1 warning (0.01 sec)

查看slave状态

mysql>show slave status;
slave02 加入master

进入deploy-mysql-slave-02-0 的 Pod,密码root

[root@master ~]# kubectl exec -itn deploy-mysql pod/deploy-mysql-slave-02-0 -- mysql -uroot -p

配置从节点(Slave)连接到主节点(Master)的参数,执行以下命令来配置它们连接到主节点

CHANGE MASTER TO 
    MASTER_HOST='deploy-mysql-master-0.deploy-mysql-master-svc.deploy-mysql.svc.cluster.local', 
    MASTER_PORT=3306, 
    MASTER_USER='root', 
    MASTER_PASSWORD='root', 
    MASTER_LOG_FILE='master-bin.000005', 
    MASTER_LOG_POS=157, 
    MASTER_CONNECT_RETRY=30, 
    GET_MASTER_PUBLIC_KEY=1;

在这里插入图片描述
启动从节点的复制进程

mysql>start slave;
Query OK,0rows affected,1 warning (0.01 sec)

查看slave状态

mysql>show slave status;
验证集群主从复制效果
  • 主节点操作会被同步到两个子节点中
  • 子节点操作不会被同步到主节点中
  • 子节点操作会同步到另一个自己点中在这里插入图片描述
标签: kubernetes mysql 容器

本文转载自: https://blog.csdn.net/m0_50978391/article/details/137965362
版权归原作者 长夜多忧思 所有, 如有侵权,请联系我们删除。

“K8s集群中部署Mysql一主两从集群”的评论:

还没有评论