首页 > 数据库 >K8S部署MySQL5.7主从集群

K8S部署MySQL5.7主从集群

时间:2024-03-05 16:57:01浏览次数:26  
标签:kubectl name MySQL5.7 xtrabackup master conf mysql K8S 主从

参考
https://blog.csdn.net/qq_43114229/article/details/124078914
https://kubernetes.io/zh-cn/docs/tasks/run-application/run-replicated-stateful-application/

MySQL主从同步架构图
image
mysql-0是master
mysql-1和mysql-2是两个备份
当mysql写的时候,找headless service中的mysql-0.mysql;当mysql读的时候,找clusterip service中的mysql读,实现读写分离。
statefulset维护三个副本,一个主两个从
因为主从的配置不同所以通过configmap来解决主从配置不同的问题

  1. 配置configmap
# cat configmap.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: mysql
  labels:
    app: mysql
data:
  master.cnf: |
    # Apply this config only on the master.
    [mysqld]
    log-bin  # 主mysql激活二进制日志
  slave.cnf: |
    # Apply this config only on slaves.
    [mysqld]
    super-read-only   # 从mysql上面设置为只读

生成配置

# kubectl apply -f configmap.yaml

查看

# kubectl get cm mysql
NAME    DATA   AGE
mysql   2      9s
  1. 创建service服务
# cat service.yaml 
apiVersion: v1
kind: Service
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  ports:
  - name: mysql
    port: 3306
  clusterIP: None
  selector:
    app: mysql
---
# Client service for connecting to any MySQL instance for reads.
# For writes, you must instead connect to the master: mysql-0.mysql.
apiVersion: v1
kind: Service
metadata:
  name: mysql-read
  labels:
    app: mysql
spec:
  ports:
  - name: mysql
    port: 3306
  selector:
    app: mysql

创建service

# kubectl apply -f service.yaml 
service/mysql created
service/mysql-read created

查看service

# kubectl get svc mysql mysql-read
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE
mysql        ClusterIP   None         <none>        3306/TCP   42s
NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)    AGE
mysql-read   ClusterIP   10.0.0.214   <none>        3306/TCP   42s
  1. statefulset配置
# cat statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  serviceName: mysql
  replicas: 2
  template:
    metadata:
      labels:
        app: mysql
    spec:
      initContainers:
      - name: init-mysql
        image: mysql:5.7
        #image: mysql:8.0.36
        command:
        - bash
        - "-c"
        - |
          set -ex
          # Generate mysql server-id from pod ordinal index.
          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
          #[[ `hostid` =~ -([0-9]+)$ ]] || exit 1
          ordinal=${BASH_REMATCH[1]}
          echo [mysqld] > /mnt/conf.d/server-id.cnf
          # Add an offset to avoid reserved server-id=0 value.
          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
          # Copy appropriate conf.d files from config-map to emptyDir.
          if [[ $ordinal -eq 0 ]]; then
            cp /mnt/config-map/master.cnf /mnt/conf.d/
          else
            cp /mnt/config-map/slave.cnf /mnt/conf.d/
          fi
        volumeMounts:
        - name: conf
          mountPath: /mnt/conf.d
        - name: config-map
          mountPath: /mnt/config-map
      - name: clone-mysql
        #image: xtrabackup:1.0
        image: 192.168.3.61/foundation/xtrabackup:1.0
        command:
        - bash
        - "-c"
        - |
          set -ex
          # Skip the clone if data already exists.
          [[ -d /var/lib/mysql/mysql ]] && exit 0
          # Skip the clone on master (ordinal index 0).
          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
          #[[ `hostid` =~ -([0-9]+)$ ]] || exit 1
          ordinal=${BASH_REMATCH[1]}
          [[ $ordinal -eq 0 ]] && exit 0
          # Clone data from previous peer.
          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
          # Prepare the backup.
          xtrabackup --prepare --target-dir=/var/lib/mysql
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
      containers:
      - name: mysql
        image: mysql:5.7
        env:
        - name: MYSQL_ALLOW_EMPTY_PASSWORD
          value: "1"
        ports:
        - name: mysql
          containerPort: 3306
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
        resources:
          requests:
            cpu: 500m
            memory: 500Mi
        livenessProbe:
          exec:
            command: ["mysqladmin", "ping"]
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
        readinessProbe:
          exec:
            # Check we can execute queries over TCP (skip-networking is off).
            command: ["mysql", "-h", "127.0.0.1", "-e", "SELECT 1"]
          initialDelaySeconds: 5
          periodSeconds: 2
          timeoutSeconds: 1
      - name: xtrabackup
       # image: xtrabackup:1.0
        image: 192.168.3.61/foundation/xtrabackup:1.0
        ports:
        - name: xtrabackup
          containerPort: 3307
        command:
        - bash
        - "-c"
        - |
          set -ex
          cd /var/lib/mysql

          # Determine binlog position of cloned data, if any.
          if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
            # XtraBackup already generated a partial "CHANGE MASTER TO" query
            # because we're cloning from an existing slave. (Need to remove the tailing semicolon!)
            cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
            # Ignore xtrabackup_binlog_info in this case (it's useless).
            rm -f xtrabackup_slave_info xtrabackup_binlog_info
          elif [[ -f xtrabackup_binlog_info ]]; then
            # We're cloning directly from master. Parse binlog position.
            [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
            rm -f xtrabackup_binlog_info xtrabackup_slave_info
            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
          fi

          # Check if we need to complete a clone by starting replication.
          if [[ -f change_master_to.sql.in ]]; then
            echo "Waiting for mysqld to be ready (accepting connections)"
            until mysql -h 127.0.0.1 -e "SELECT 1"; do sleep 1; done

            echo "Initializing replication from clone position"
            mysql -h 127.0.0.1 \
                  -e "$(<change_master_to.sql.in), \
                          MASTER_HOST='mysql-0.mysql', \
                          MASTER_USER='root', \
                          MASTER_PASSWORD='', \
                          MASTER_CONNECT_RETRY=10; \
                        START SLAVE;" || exit 1
            # In case of container restart, attempt this at-most-once.
            mv change_master_to.sql.in change_master_to.sql.orig
          fi

          # Start a server to send backups when requested by peers.
          exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
            "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root"
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
      volumes:
      - name: conf
        emptyDir: {}
      - name: config-map
        configMap:
          name: mysql
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      storageClassName: gluster-heketi-storageclass
      resources:
        requests:
          storage: 10Gi

注意配置storageClassName动态存储

创建statefulset和pvc

# kubectl apply -f statefulset.yaml

查看创建的pvc
设置了几个副本则有几个pvc

# kubectl get pvc data-mysql-0 data-mysql-1
NAME           STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS                  AGE
data-mysql-0   Bound    pvc-980d613d-dac3-11ee-b17f-525400e71cb5   10Gi       RWO            gluster-heketi-storageclass   42m
NAME           STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS                  AGE
data-mysql-1   Bound    pvc-ae563992-dac3-11ee-b17f-525400e71cb5   10Gi       RWO            gluster-heketi-storageclass   42m

查看初始化日志输出

# kubectl logs mysql-0 -c init-mysql
++ hostname
+ [[ mysql-0 =~ -([0-9]+)$ ]]
+ ordinal=0
+ echo '[mysqld]'
+ echo server-id=100
+ [[ 0 -eq 0 ]]
+ cp /mnt/config-map/master.cnf /mnt/conf.d/

查看pod的配置文件

# kubectl exec mysql-0 -c mysql -- ls /etc/mysql/conf.d
master.cnf
server-id.cnf
# kubectl exec mysql-1 -c mysql -- ls /etc/mysql/conf.d
server-id.cnf
slave.cnf

查看配置文件内容

# kubectl exec mysql-0 -c mysql  -- cat /etc/mysql/conf.d/master.cnf
# Apply this config only on the master.
[mysqld]
log-bin  # 主mysql激活二进制日志
# kubectl exec mysql-1 -c mysql  -- cat /etc/mysql/conf.d/slave.cnf
# Apply this config only on slaves.
[mysqld]
super-read-only   # 从mysql上面设置为只读

查看生成的Pod

# kubectl get pod mysql-0 mysql-1
NAME      READY   STATUS    RESTARTS   AGE
mysql-0   2/2     Running   0          5m32s
NAME      READY   STATUS    RESTARTS   AGE
mysql-1   2/2     Running   0          5m22s
  1. 创建NodePort端口
    K8S集群内可以使用DNS使用域名mysql-0.mysql访问
    在集群外部访问创建NodePort
# cat mysql-service.yaml 
apiVersion: v1
kind: Service
metadata:
  creationTimestamp: null
  labels:
    app: mysql
    controller-revision-hash: mysql-79b5fcf7cc
    statefulset.kubernetes.io/pod-name: mysql-0
  name: mysql-0
spec:
  ports:
  - port: 3306
    protocol: TCP
    targetPort: 3306
    nodePort: 33306
  selector:
    app: mysql
    controller-revision-hash: mysql-79b5fcf7cc
    statefulset.kubernetes.io/pod-name: mysql-0
  type: NodePort
status:
  loadBalancer: {}

创建svc

#  kubectl apply -f mysql-service.yaml 

查看svc

# kubectl get svc mysql-0
NAME      TYPE       CLUSTER-IP   EXTERNAL-IP   PORT(S)          AGE
mysql-0   NodePort   10.0.0.118   <none>        3306:33306/TCP   44s

访问并修改root密码

默认root无密码 通过node节点ip和NodePort端口访问

# mysql -uroot -p -h192.168.3.65 -P 33306

删除用户并新建用户设置密码并授权

MySQL [(none)]> drop user root@'%';
Query OK, 0 rows affected (0.02 sec)

MySQL [(none)]> create user root@'%' identified by 'password';
Query OK, 0 rows affected (0.01 sec)

MySQL> grant all on *.* to 'root'@'%';
Query OK, 0 rows affected (0.01 sec)

MySQL [(none)]> flush privileges;
Query OK, 0 rows affected (0.01 sec)

登录从节点查看主从同步状态

# kubectl exec -it mysql-1 bash
mysql> show slave status\G
*************************** 1. row ***************************
               Slave_IO_State: Waiting for master to send event
                  Master_Host: mysql-0.mysql
                  Master_User: root
                  Master_Port: 3306
                Connect_Retry: 10
              Master_Log_File: mysql-0-bin.000005
          Read_Master_Log_Pos: 2062
               Relay_Log_File: mysql-1-relay-bin.000005
                Relay_Log_Pos: 2279
        Relay_Master_Log_File: mysql-0-bin.000005
             Slave_IO_Running: Yes
            Slave_SQL_Running: Yes

以下两个状态为Yes则代表主从状态正常
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
4. 清理

# kubectl delete -f configmap.yaml 
# kubectl delete -f service.yaml 
# kubectl delete -f mysql-service.yaml 
# kubectl delete -f statefulset.yaml

不会清理pvc手动删除pvc

# kubectl delete pvc data-mysql-0
persistentvolumeclaim "data-mysql-0" deleted
# kubectl delete pvc data-mysql-1
persistentvolumeclaim "data-mysql-1" deleted

把statefulset的副本数修改为3则为一主两从的架构

标签:kubectl,name,MySQL5.7,xtrabackup,master,conf,mysql,K8S,主从
From: https://www.cnblogs.com/minseo/p/18054392

相关文章

  • CentOS 7单机部署 Redis 主从复制
    下面是一个完整的、步骤明确的指南,包括如何在CentOS7上以非root用户(在本例中为appworker,属于appworkergroup组)安装和配置Redis主从复制,设置目录权限,以及进行基本的连接测试和维护操作。1.环境准备创建用户和组sudogroupaddappworkergroup#创建一个名为appw......
  • K8s中Role(ClusterRole)资源类型rules字段详解
    在Kubernetes(K8s)中,Role资源类型的rules字段用于定义哪些操作(verbs)可以在哪些资源(resources)上执行。Role是一种命名空间级别的资源,它允许你对命名空间内的资源进行细粒度的访问控制。resources:resources字段指定了角色可以访问的资源类型。这些资源类型可以是KubernetesAPI中......
  • 未完成编辑 Linux CentOS7.6使用腾讯Yum源安装MySQL5.7,执行mysql-secure-installation
    学习安装MySQL时发现官方源很慢,试了国内腾讯源快,记录一下LinuxCentOS7.6前置环境:CPU1内存4GB硬盘SCSI20GB网络模式桥接系统内为自动DHCPpingqq.com可通互联网以下为MySQL5.7安装步骤编辑新repo库路径:/etc/yum.repos.d/mysql-community.repovi/etc/yum.repos......
  • K8S集群Master节点怎么迁移
    需求使用虚拟机搭建了一台K8S的Master节点,现在需要迁移至物理机因为搭建K8S集群Master节点的时候使用了节点的IP生成证书所以新的物理机需要何原Master节点的IP一致复制配置文件和二进制文件#scp-r/opt/kubernetes/[email protected]:/opt/kubernetes/复制service......
  • k8s名词巩固
    DeploymentDeployment控制器通过ReplicaSet来创建并管理Pod,同时具有版本升降级的功能。ReplicaSet相对于ReplicationController来言拥有更先进的标签选择器,ReplicationController只支持旧式的标签选择器。DaemonSetDaemonSet可以确保每个工作节点上最多运行一个应用副本,这个......
  • K8S集群调度
    K8S集群调度K8S的watch机制Kubernetes是通过List-Watch的机制进行每个组件的协作,保持数据同步的,每个组件之间的设计实现了解耦。用户是通过kubectl根据配置文件,向APIServer发送命令,在Node节点上面建立Pod和Container。APIServer经过API调用,权限控制,调用资源......
  • k8s有关问题
    1.pod报错:unabletoensurepodcontainerexists:failedtocreatecontainerfor[kubepodsburstablepod7e45f702-c697-4b39-b34b-db8792445622]:mkdir/sys/fs/cgroup/memory/kubepods/burstable/pod7e45f702-c697-4b39-b34b-db8792445622:cannotallocatememory解决:......
  • 在K8S中,如何在指定节点上部署Pod呢?
    在Kubernetes(K8s)中,要在指定节点上部署Pod,可以使用两种方法:方法一:使用nodeName字段明确指定在Pod的YAML定义中,可以直接在.spec.nodeName字段指定目标节点的名称。这样,Pod将会被调度到指定的节点上。示例YAML配置:apiVersion:v1kind:Podmetadata:name:my-pod-on-specif......
  • 在K8S中,Resource Quotas是什么?如何做资源管理的?
    在Kubernetes(K8s)中,ResourceQuotas是一种集群管理员用来限制Namespace内资源消耗总量的机制。这种机制允许管理员对特定Namespace定义资源使用上限,确保Namespace内的用户或团队不会过度消耗集群资源,进而影响其他Namespace或整个集群的稳定性。ResourceQuotas具体是如何工......
  • 基于现有k8S 集群 CA 证书更新100年
    #先提前编译kubeadm到100年1、先备份conf文件和证书文件cp-rp /etc/kubernetes//etc/kubernetes.bak2、生成新的crt证书,默认在/etc/kubernetes/pki路径fori in cafront-proxy-caapiserver-kubelet-clientfront-proxy-clientapiserver;dokubeadminitphase......