微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

8.2 k8s 基于StatefulSet运行mysql 一主多从 ,数据通过pv/pvc结合NFS服务器持久化

1.准备MysqL和xtrabackup镜像

下载MysqL官方镜像并上传到本地harbor

docker pull MysqL:5.7
docker tag m ysql:5.7 192.168.1.110/base/MysqL:5.7
docker push 192.168.1.110/base/MysqL:5.7

下载xtrabackup镜像并上传到本地harbor

docker pull registry.cn-hangzhou.aliyuncs.com/hxpdocker/xtrabackup:1.0
docker tag registry.cn-hangzhou.aliyuncs.com/hxpdocker/xtrabackup:1.0 192.168.1.110/base/xtrabackup:1.0
docker push 192.168.1.110/base/xtrabackup:1.0

2.为MysqL数据目录准备PV

nfs创建目录

# mkdir /data/k8s-data/MysqL/MysqL-datadir-1 -p
# mkdir /data/k8s-data/MysqL/MysqL-datadir-2 -p
# mkdir /data/k8s-data/MysqL/MysqL-datadir-3 -p
# mkdir /data/k8s-data/MysqL/MysqL-datadir-4 -p
# mkdir /data/k8s-data/MysqL/MysqL-datadir-5 -p

编写pv的yaml

root@k8-deploy:~/k8s-yaml/MysqL# cat pv/MysqL-datadir-pv.yaml 
apiVersion: v1
kind: PersistentVolume
Metadata:
  name: MysqL-datadir-1
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  nfs:
    server: 192.168.2.10
    path: /data/k8s-data/MysqL/MysqL-datadir-1
---
apiVersion: v1
kind: PersistentVolume
Metadata:
  name: MysqL-datadir-2
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  nfs:
    server: 192.168.2.10
    path: /data/k8s-data/MysqL/MysqL-datadir-2
---
apiVersion: v1
kind: PersistentVolume
Metadata:
  name: MysqL-datadir-3
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  nfs:
    server: 192.168.2.10
    path: /data/k8s-data/MysqL/MysqL-datadir-3
---
apiVersion: v1
kind: PersistentVolume
Metadata:
  name: MysqL-datadir-4
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  nfs:
    server: 192.168.2.10
    path: /data/k8s-data/MysqL/MysqL-datadir-4
---
apiVersion: v1
kind: PersistentVolume
Metadata:
  name: MysqL-datadir-5
spec:
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  nfs:
    server: 192.168.2.10
    path: /data/k8s-data/MysqL/MysqL-datadir-5

创建PV

root@k8-deploy:~/k8s-yaml/MysqL# kubectl apply -f MysqL-datadir-pv.yaml 
persistentvolume/MysqL-datadir-1 created
persistentvolume/MysqL-datadir-2 created
persistentvolume/MysqL-datadir-3 created
persistentvolume/MysqL-datadir-4 created
persistentvolume/MysqL-datadir-5 created

root@k8-deploy:~/k8s-yaml/MysqL# kubectl get pv
NAME                     CAPACITY   ACCESS MODES   RECLaim POLICY   STATUS      CLaim                           STORAGECLASS   REASON   AGE
MysqL-datadir-1          10Gi       RWO            Retain           Available                                                           3s
MysqL-datadir-2          10Gi       RWO            Retain           Available                                                           3s
MysqL-datadir-3          10Gi       RWO            Retain           Available                                                           3s
MysqL-datadir-4          10Gi       RWO            Retain           Available                                                           3s
MysqL-datadir-5          10Gi       RWO            Retain           Available                                                           3s

3.部署StatefulSet的MysqL集群

3.1 编写yaml文件

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    
  slave.cnf: |
    # Apply this config only on slaves.
    [MysqLd]
    super-read-only    

MysqL-services.yaml

 Headless service for stable DNS entries of StatefulSet members.
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

statefulset.yaml

# cat MysqL-statefulset.yaml 
apiVersion: apps/v1
kind: StatefulSet
Metadata:
  name: MysqL
spec:
  selector:
    matchLabels:
      app: MysqL
  serviceName: MysqL
  replicas: 3
  template:
    Metadata:
      labels:
        app: MysqL
    spec:
      initContainers:
      - name: init-MysqL
        image: 192.168.1.110/base/MysqL:5.7
        command:
        - bash
        - "-c"
        - |
          set -ex
          # Generate MysqL server-id from pod ordinal index.
          [[ `hostname` =~ -([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: 192.168.1.110/base/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
          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: 192.168.1.110/base/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: 1Gi
        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: 192.168.1.110/base/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"]
      resources:
        requests:
          storage: 10Gi

3.2 创建集群

kubectl apply -f MysqL-configmap.yaml
kubectl apply -f MysqL-services.yaml
kubectl apply -f MysqL-statefulset.yaml

3.3 测试集群

查看pod是否创建成功

root@k8-deploy:~/k8s-yaml/MysqL# kubectl get pod
NAME      READY   STATUS    RESTARTS   AGE
MysqL-0   2/2     Running   0          3m13s
MysqL-1   2/2     Running   1          2m44s
MysqL-2   2/2     Running   1          99s

进入pod查看挂载pv

root@k8-deploy:~/k8s-yaml/MysqL# kubectl exec MysqL-0 -it -- bash
root@MysqL-0:/# df -h
Filesystem                                               Size  Used Avail Use% Mounted on
...
192.168.2.10:/data/k8s-data/MysqL/MysqL-datadir-4/MysqL   98G   20G   74G  21% /var/lib/MysqL
...

进入MysqL-0 pod(MysqL主)查看MysqL状态,并创建测试数据库

root@MysqL-0:/# MysqL
Welcome to the MysqL monitor.  Commands end with ; or \g.
Your MysqL connection id is 148
Server version: 5.7.36-log MysqL Community Server (GPL)

copyright (c) 2000, 2021, 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> show master status\G;
*************************** 1. row ***************************
             File: MysqL-0-bin.000003
         Position: 154
     binlog_Do_DB: 
 binlog_Ignore_DB: 
Executed_Gtid_Set: 
1 row in set (0.00 sec)

ERROR: 
No query specified

MysqL> shwo databases;
ERROR 1064 (42000): You have an error in your sql Syntax; check the manual that corresponds to your MysqL server version for the right Syntax to use near 'shwo databases' at line 1
MysqL> show  databases;  
+------------------------+
| Database               |
+------------------------+
| @R_677_4045@ion_schema     |
| MysqL                  |
| performance_schema     |
| sys                    |
| xtrabackup_backupfiles |
+------------------------+
5 rows in set (0.04 sec)

MysqL> create database yan_test;
Query OK, 1 row affected (0.02 sec)

MysqL> show  databases;
+------------------------+
| Database               |
+------------------------+
| @R_677_4045@ion_schema     |
| MysqL                  |
| performance_schema     |
| sys                    |
| xtrabackup_backupfiles |
| yan_test               |
+------------------------+
6 rows in set (0.01 sec)

MysqL> exit

依次查看其他从库的主从同步状态

root@MysqL-1:/# MysqL
Welcome to the MysqL monitor.  Commands end with ; or \g.
Your MysqL connection id is 140
Server version: 5.7.36 MysqL Community Server (GPL)

copyright (c) 2000, 2021, 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> 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.000003
          Read_Master_Log_Pos: 325
               Relay_Log_File: MysqL-1-relay-bin.000002
                Relay_Log_Pos: 493
        Relay_Master_Log_File: MysqL-0-bin.000003
             Slave_IO_Running: Yes
            Slave_sql_Running: Yes
...

MysqL> show databases;
+------------------------+
| Database               |
+------------------------+
| @R_677_4045@ion_schema     |
| MysqL                  |
| performance_schema     |
| sys                    |
| xtrabackup_backupfiles |
| yan_test               |
+------------------------+
6 rows in set (0.02 sec)

查看MysqL的数据是否写入nfs

root@k8-deploy:~/k8s-yaml/MysqL# tree -L 2 /data/k8s-data/MysqL/
/data/k8s-data/MysqL/
├── MysqL-datadir-1
│   └── MysqL
├── MysqL-datadir-2
│   └── MysqL
├── MysqL-datadir-3
├── MysqL-datadir-4
│   └── MysqL
└── MysqL-datadir-5

4.扩缩容测试

4.1 将集群副本增加到4个

root@k8-deploy:~/k8s-yaml/MysqL# kubectl scale -n default statefulset MysqL --replicas=4
statefulset.apps/MysqL scaled

root@k8-deploy:~/k8s-yaml/MysqL# kubectl get pod
NAME      READY   STATUS    RESTARTS   AGE
MysqL-0   2/2     Running   0          13m
MysqL-1   2/2     Running   1          12m
MysqL-2   2/2     Running   1          11m
MysqL-3   1/2     Running   1          24s

4.2 查看增加MysqL-3的主从状态

root@MysqL-3:/# MysqL
Welcome to the MysqL monitor.  Commands end with ; or \g.
Your MysqL connection id is 13
Server version: 5.7.36 MysqL Community Server (GPL)

copyright (c) 2000, 2021, 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> 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.000003
          Read_Master_Log_Pos: 325
               Relay_Log_File: MysqL-3-relay-bin.000002
                Relay_Log_Pos: 322
        Relay_Master_Log_File: MysqL-0-bin.000003
             Slave_IO_Running: Yes
            Slave_sql_Running: Yes
...

MysqL> show databases;
+------------------------+
| Database               |
+------------------------+
| @R_677_4045@ion_schema     |
| MysqL                  |
| performance_schema     |
| sys                    |
| xtrabackup_backupfiles |
| yan_test               |
+------------------------+
6 rows in set (0.02 sec)

4.3 查看nfs MysqL数据目录

root@k8-deploy:~/k8s-yaml/MysqL# tree -L 2 /data/k8s-data/MysqL/
/data/k8s-data/MysqL/
├── MysqL-datadir-1
│   └── MysqL
├── MysqL-datadir-2
│   └── MysqL
├── MysqL-datadir-3
│   └── MysqL
├── MysqL-datadir-4
│   └── MysqL
└── MysqL-datadir-5

9 directories, 0 files

4.4 将副本数缩容至2个

root@k8-deploy:~/k8s-yaml/MysqL# kubectl scale -n default statefulset MysqL --replicas=2
statefulset.apps/MysqL scaled

4.4 查看pod缩容的过程(-w 参数)

root@k8-deploy:~/k8s-yaml/MysqL# kubectl get pod -w
NAME      READY   STATUS        RESTARTS   AGE
MysqL-0   2/2     Running       0          47m
MysqL-1   2/2     Running       1          46m
MysqL-2   2/2     Running       1          45m
MysqL-3   2/2     Terminating   1          34m
MysqL-3   0/2     Terminating   1          34m
MysqL-3   0/2     Terminating   1          34m
MysqL-3   0/2     Terminating   1          34m
MysqL-2   2/2     Terminating   1          46m

root@k8-deploy:~/k8s-yaml/MysqL# kubectl get pod
NAME      READY   STATUS    RESTARTS   AGE
MysqL-0   2/2     Running   0          48m
MysqL-1   2/2     Running   1          47m

4.4 再次查看MysqL-1的主从状态是否正常。

# kubectl exec MysqL-1 -it -- 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.000003
          Read_Master_Log_Pos: 325
               Relay_Log_File: MysqL-1-relay-bin.000002
                Relay_Log_Pos: 493
        Relay_Master_Log_File: MysqL-0-bin.000003
             Slave_IO_Running: Yes
            Slave_sql_Running: Yes

4.4 缩容后再次查看nfs上MysqL的数据目录(k8s并不会自动删除清理,需要手动操作)

root@k8-deploy:~/k8s-yaml/MysqL# tree -L 2 /data/k8s-data/MysqL/
/data/k8s-data/MysqL/
├── MysqL-datadir-1
│   └── MysqL
├── MysqL-datadir-2
│   └── MysqL
├── MysqL-datadir-3
│   └── MysqL
├── MysqL-datadir-4
│   └── MysqL
└── MysqL-datadir-5

9 directories, 0 files

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐