基于StatefulSet控制器运行MySQL一主多从

  基于StatefulSet的mysql主从架构

  下载xtrabackup镜像

root@deploy:/dockerfile/project/mysql/pv# docker pull registry.cn-hangzhou.aliyuncs.com/liangxiaohui/xtrabackup:1.0
root@deploy:/dockerfile/project/redis-cluster# docker tag registry.cn-hangzhou.aliyuncs.com/liangxiaohui/xtrabackup:1.0 harbor.cncf.net/project/xtrabackup:1.0
root@deploy:/dockerfile/project/redis-cluster# docker push harbor.cncf.net/project/xtrabackup:1.0

 

       拉取mysql镜像

root@deploy:/dockerfile/project/redis-cluster# docker pull mysql:5.7.36
root@deploy:/dockerfile/project/redis-cluster# docker tag mysql:5.7.36 harbor.cncf.net/project/mysql:5.7.36
root@deploy:/dockerfile/project/redis-cluster# docker push harbor.cncf.net/project/mysql:5.7.36

 

       创建nfs共享目录

root@harbor:/data/k8sdata# mkdir mysql/mysql-{1..3} -p
root@harbor:/data/k8sdata/mysql# cat /etc/exports
/data/volumes2 *(rw,sync,no_root_squash)

root@harbor:/data/k8sdata/mysql# exportfs -r
root@harbor:/data/k8sdata/mysql# showmount -e localhost
Export list for localhost:
/data/volumes2 *
/data/volumes  *
/data/k8sdata  *
root@harbor:/data/k8sdata/mysql# exportfs -r

 

       创建pv

root@deploy:/dockerfile/project/mysql/pv# cat mysql-persistentvolume.yaml 
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysql-datadir-1
spec:
  capacity:
    storage: 50Gi
  accessModes:
    - ReadWriteOnce
  nfs:
    path: /data/k8sdata/mysql/mysql-1 
    server: 192.168.119.2
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysql-datadir-2
spec:
  capacity:
    storage: 50Gi
  accessModes:
    - ReadWriteOnce
  nfs:
    path: /data/k8sdata/mysql/mysql-2
    server: 192.168.119.2
---
apiVersion: v1
kind: PersistentVolume
metadata:
  name: mysql-datadir-3
spec:
  capacity:
    storage: 50Gi
  accessModes:
    - ReadWriteOnce
  nfs:
    path: /data/k8sdata/mysql/mysql-3
    server: 192.168.119.2

 

      

  创建命名空间

root@deploy:/dockerfile/project/mysql# kubectl create ns mysql-test
root@deploy:/dockerfile/project/mysql# kubectl config set-context --namespace mysql-test --current 
Context "context-cluster1" modified.

 

       创建mysql主从的配置文件configmap

       指定主库的端口号为3360;

  禁止从库写入端口号为默认的3306

root@deploy:/dockerfile/project/mysql# cat mysql-configmap.yaml 
apiVersion: v1
kind: ConfigMap
metadata:
  name: mysql
  namespace: mysql-test
  labels:
    app: mysql
data:
  master.cnf: |
    # Master配置
    [mysqld]
    port=3360
    log-bin=mysql-bin
    skip-name-resolve
    lower_case_table_names=1
  slave.cnf: |
    # Slave配置
    [mysqld]
    super-read-only
    skip-name-resolve
    log-bin=mysql-bin
    replicate-ignore-db=mysql

 

       创建主库localhost的root账户密码secret

root@deploy:/dockerfile/project/mysql#echo -n "123456" | base64
MTIzNDU2

root@deploy:/dockerfile/project/mysql# vim mysql-secret.yaml 
apiVersion: v1
kind: Secret
metadata:
  name: mysql-secret
  namespace: mysql-test
  labels:
    app: mysql
type: Opaque
data:
  password: MTIzNDU2

 

创建mysql service,根据生产需要是否暴露对外访问主库或者从库的端口

所有的写请求,都使用mysql主库进行访问。

所有读请求,则由service分配给主库和任意从库进行访问

root@deploy:/dockerfile/project/mysql# cat mysql-services.yaml 
# Headless service for stable DNS entries of StatefulSet members.
apiVersion: v1
kind: Service
metadata:
  namespace: mysql-test
  name: mysql
  labels:
    app: mysql
spec:
  ports:
  - name: mysql-master
    port: 3360
  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
  namespace: mysql-test
  labels:
    app: mysql
spec:
  type: NodePort
  ports:
  - name: mysql-master
    port: 3360
    targetPort: 3360
    nodePort: 33600
  - name: mysql-slave
    port: 3306
    targetPort: 3306
    nodePort: 33060
  selector:
    app: mysql

 

  创建mysql的statefulset

root@deploy:/dockerfile/project/mysql# cat mysql.yaml 
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
  namespace: mysql-test
  labels:
    app: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  serviceName: mysql
  replicas: 2
  template:
    metadata:
      labels:
        app: mysql
    spec:
      initContainers:
      - name: init-mysql
        image: harbor.cncf.net/project/mysql:5.7.36
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-secret
              key: password
        command:
        - bash
        - "-c"
        - |
          set -ex
          # 从Pod的序号,生成server-id
          [[ $(hostname) =~ -([0-9]+)$ ]] || exit 1
          ordinal=${BASH_REMATCH[1]}
          echo [mysqld] > /mnt/conf.d/server-id.cnf
          # 由于server-id不能为0,因此给ID加100来避开它
          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
          # 如果Pod的序号为0,说明它是Master节点,从ConfigMap里把Master的配置文件拷贝到/mnt/conf.d目录下
          # 否则,拷贝ConfigMap里的Slave的配置文件
          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: harbor.cncf.net/project/xtrabackup:1.0
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-secret
              key: password
        command:
        - bash
        - "-c"
        - |
          set -ex
          # 拷贝操作只需要在第一次启动时进行,所以数据已经存在则跳过
          [[ -d /var/lib/mysql/mysql ]] && exit 0
          # Master 节点(序号为 0)不需要这个操作
          [[ $(hostname) =~ -([0-9]+)$ ]] || exit 1
          ordinal=${BASH_REMATCH[1]}
          [[ $ordinal == 0 ]] && exit 0
          # 使用ncat指令,远程地从前一个节点拷贝数据到本地
          ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
          # 执行 --prepare,这样拷贝来的数据就可以用作恢复了
          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: harbor.cncf.net/project/mysql:5.7.36
        env:
 #        - name: MYSQL_ALLOW_EMPTY_PASSWORD
 #          value: "1"
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-secret
              key: password
        ports:
        - name: mysql
          containerPort: 3360
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
        resources:
          requests:
            cpu: 500m
            memory: 1Gi
        livenessProbe:
          exec:
            command: ["mysqladmin", "ping", "-uroot", "-p123456"]
          initialDelaySeconds: 30
          periodSeconds: 10
          timeoutSeconds: 5
        readinessProbe:
          exec:
            command: ["mysql","-uroot", "-p123456", "-e", "SELECT 1"]
          initialDelaySeconds: 5
          periodSeconds: 2
          timeoutSeconds: 1
      - name: xtrabackup
        image: harbor.cncf.net/project/xtrabackup:1.0
        ports:
        - name: xtrabackup
          containerPort: 3307
        env:
        - name: MYSQL_ROOT_PASSWORD
          valueFrom:
            secretKeyRef:
              name: mysql-secret
              key: password
        command:
        - bash
        - "-c"
        - |
          set -ex
          cd /var/lib/mysql
          # 从备份信息文件里读取MASTER_LOG_FILE和MASTER_LOG_POS这2个字段的值,用来拼装集群初始化SQL
          if [[ -f xtrabackup_slave_info ]]; then
            # 如果xtrabackup_slave_info文件存在,说明这个备份数据来自于另一个Slave节点
            # 这种情况下,XtraBackup工具在备份的时候,就已经在这个文件里自动生成了“CHANGE MASTER TO”SQL语句
            # 所以,只需要把这个文件重命名为change_master_to.sql.in,后面直接使用即可
            mv xtrabackup_slave_info change_master_to.sql.in
            # 所以,也就用不着xtrabackup_binlog_info了
            rm -f xtrabackup_binlog_info
          elif [[ -f xtrabackup_binlog_info ]]; then
            # 如果只是存在xtrabackup_binlog_info文件,说明备份来自于Master节点,就需要解析这个备份信息文件,读取所需的两个字段的值
            [[ $(cat xtrabackup_binlog_info) =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
            rm xtrabackup_binlog_info
            # 把两个字段的值拼装成SQL,写入change_master_to.sql.in文件
            echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
                  MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
          fi
          # 如果存在change_master_to.sql.in,就意味着需要做集群初始化工作
          if [[ -f change_master_to.sql.in ]]; then
            # 但一定要先等MySQL容器启动之后才能进行下一步连接MySQL的操作
            echo "Waiting for mysqld to be ready(accepting connections)"
            until mysql -h 127.0.0.1 -uroot -p${MYSQL_ROOT_PASSWORD} -e "SELECT 1"; do sleep 1; done
            echo "Initializing replication from clone position"
            # 将文件change_master_to.sql.in改个名字
            # 防止这个Container重启的时候,因为又找到了change_master_to.sql.in,从而重复执行一遍初始化流程
            mv change_master_to.sql.in change_master_to.sql.orig
            # 使用change_master_to.sql.orig的内容,也就是前面拼装的SQL,组成一个完整的初始化和启动Slave的SQL语句
            mysql -h 127.0.0.1 -uroot -p${MYSQL_ROOT_PASSWORD} << EOF
          $(< change_master_to.sql.orig),
            MASTER_HOST='mysql-0.mysql.mysql-test',
            MASTER_USER='root',
            MASTER_PORT=3360,
            MASTER_PASSWORD='${MYSQL_ROOT_PASSWORD}',
            MASTER_CONNECT_RETRY=10;
          START SLAVE;
          EOF
          fi
          # 使用ncat监听3307端口。
          # 它的作用是,在收到传输请求的时候,直接执行xtrabackup --backup命令,备份MySQL的数据并发送给请求者
          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 --password=${MYSQL_ROOT_PASSWORD}"
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
      volumes:
      - name: conf
        emptyDir: {}
      - name: config-map
        configMap:
          name: mysql
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 10Gi

 

      

  验证主从服务同步状态

root@deploy:/dockerfile/project/mysql# kubectl exec -it mysql-1 -c mysql -- bash -c "mysql -uroot -p123456 -e 'show slave status \G'"

  

  插入数据访问验证

root@deploy:/dockerfile/project/mysql# kubectl exec mysql-0 -c mysql -- bash -c "mysql -uroot -p123456 -P 3360 -e 'create database cncf'"
mysql: [Warning] Using a password on the command line interface can be insecure.
root@deploy:/dockerfile/project/mysql# kubectl exec mysql-0 -c mysql -- bash -c "mysql -uroot -p123456 -P 3360 -e 'use cncf;create table test(id int);'"
mysql: [Warning] Using a password on the command line interface can be insecure.
root@deploy:/dockerfile/project/mysql# kubectl exec mysql-0 -c mysql -- bash -c "mysql -uroot -p123456 -P 3360 -e 'use cncf;insert into test values(1)'"
mysql: [Warning] Using a password on the command line interface can be insecure.
root@deploy:/dockerfile/project/mysql# kubectl exec mysql-1 -c mysql -- bash -c "mysql -uroot -p123456 -e 'use cncf;select * from test

 

 

  扩容mysql从库节点

       修改statefulset副本数量

      

   对外访问mysql主从验证

       查看svc

      

   访问主库

      

   访问表数据

      

  写入数据

      

  从库访问

      

   读取表数据

 

      

  从库插入数据测试.

       符合结果:插入数据失败

 

posted @ 2022-08-19 21:11  PunchLinux  阅读(101)  评论(0编辑  收藏  举报