k8s(七)—statefullset部署mysql主从集群

1 使用statefullset部署mysql主从集群

k8s(七)—statefullset部署mysql主从集群_第1张图片mysql-0是master
mysql-1和mysql-2是两个备份
当mysql写的时候,找headless service中的mysql-0.mysql;当mysql读的时候,找clusterip service中的mysql读,实现读写分离。
statefulset维护三个副本,一个主两个从
因为主从的配置不同所以通过configmap来解决主从配置不同的问题
部署mysql文档

1.1配置configmap(创建mysql配置)

[root@server2 statefulset]# mkdir mysql
[root@server2 statefulset]# cd mysql/
[root@server2 mysql]# \vi cm.yaml    将官网的例子复制过来
apiVersion: v1
kind: ConfigMap
metadata:
  name: mysql
  labels:
    app: mysql
data:
  master.cnf: |
    [mysqld]
    log-bin     # 主mysql激活二进制日志
  slave.cnf: |
    [mysqld]
    super-read-only     # 从mysql上面设置为只读
[root@server2 mysql]# kubectl apply -f cm.yaml   运行
configmap/mysql created
[root@server2 mysql]# kubectl get cm   
NAME               DATA   AGE
kube-root-ca.crt   1      7h40m
mysql              2      13m   

1.2创建service服务

[root@server2 mysql]# \vi svc.yaml   将官网的例子复制过来,然后用vim打开
[root@server2 mysql]# vim svc.yaml   创建两个svc,主要用于读写分离
apiVersion: v1
kind: Service
metadata:
  name: mysql
  labels:
    app: mysql      
spec:
  ports:
  - name: mysql    负责写
    port: 3306
  clusterIP: None
  selector:
    app: mysql
---
apiVersion: v1
kind: Service
metadata:
  name: mysql-read     只读
  labels:
    app: mysql
spec:
  ports:
  - name: mysql
    port: 3306
  selector:
    app: mysql
[root@server2 mysql]# kubectl apply -f svc.yaml  创建
service/mysql created
service/mysql-read created
[root@server2 mysql]# kubectl get svc  查看svc,创建成功
NAME         TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)    AGE
kubernetes   ClusterIP   10.96.0.1               443/TCP    7h39m
mysql        ClusterIP   None                    3306/TCP   28s
mysql-read   ClusterIP   10.101.37.222           3306/TCP   28s

1.3 statefulset配置

[root@server1 ~]# docker pull mysql:5.7   拉取mysql ,注意版本必须是5.7
[root@foundation50 k8s]# scp  mysql-xtrabackup.tar server1:
[root@server1 ~]# docker load -i mysql-xtrabackup.tar  导入镜像
[root@server1 harbor]# docker push reg.westos.org/library/mysql:5.7   上传镜像到仓库
[root@server1 harbor]# docker push reg.westos.org/library/xtrabackup:1.0 上传镜像到仓库
[root@server2 mysql]# vim deploy.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: mysql:5.7
        command:
        - bash
        - "-c"
        - |
          set -ex
          # Generate mysql server-id from pod ordinal index.
          [[ `hostname` =~ -([0-9]+)$ ]] || exit 1  过滤第一个pod名mysql,其中hostname表示容器内pod名字
          ordinal=${BASH_REMATCH[1]}   表示拿取第一个数字0
          echo [mysqld] > /mnt/conf.d/server-id.cnf   创建一个server-id.cnf  文件,往里面写mysqld表示这个文件里的配置针对server生效
          # Add an offset to avoid reserved server-id=0 value.
          echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf   往server-id.conf 追加一条server-id=100+上面取到的数字
          # Copy appropriate conf.d files from config-map to emptyDir.  拷贝conf.d 文件到空卷
          if [[ $ordinal -eq 0 ]]; then   如果取到的数字为0
            cp /mnt/config-map/master.cnf /mnt/conf.d/  拷贝master
          else
            cp /mnt/config-map/slave.cnf /mnt/conf.d/    否则拷贝slave
          fi   
        volumeMounts:
        - name: conf
          mountPath: /mnt/conf.d
        - name: config-map
          mountPath: /mnt/config-map
      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: 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
      volumes:
      - name: conf
        emptyDir: {}
      - name: config-map
        configMap:
          name: mysql
  volumeClaimTemplates:      
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 10Gi  
[root@server2 mysql]# kubectl apply -f deploy.yaml       创建	
[root@server2 mysql]# kubectl get pod
NAME      READY   STATUS    RESTARTS   AGE
mysql-0   1/1     Running   0          71s
[root@server2 mysql]# kubectl get pv   pv已经生成
NAME                                       CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                  STORAGECLASS          REASON   AGE
pvc-179b1b5e-3d25-4741-8458-a99b18f175de   1Gi        RWX            Delete           Bound    default/test-claim     managed-nfs-storage            5h6m
pvc-4b2ad3b8-d156-429a-bc7a-f6616534e14f   10Gi       RWO            Delete           Bound    default/data-mysql-0   managed-nfs-storage            5h
[root@server2 mysql]# kubectl get pvc   pvc已经生成
NAME           STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS          AGE
data-mysql-0   Bound    pvc-4b2ad3b8-d156-429a-bc7a-f6616534e14f   10Gi       RWO            managed-nfs-storage   5h
test-claim     Bound    pvc-179b1b5e-3d25-4741-8458-a99b18f175de   1Gi        RWX            managed-nfs-storage   5h6m
[root@server1 ~]# cd /nfsdata/   查看共享目录
[root@server1 nfsdata]# ls
default-data-mysql-0-pvc-4b2ad3b8-d156-429a-bc7a-f6616534e14f
[root@server1 nfsdata]# cd default-data-mysql-0-pvc-4b2ad3b8-d156-429a-bc7a-f6616534e14f/  
[root@server1 default-data-mysql-0-pvc-4b2ad3b8-d156-429a-bc7a-f6616534e14f]# ls
mysql   创建的子目录
[root@server1 mysql]# ls   
auto.cnf         ibdata1             mysql-0-bin.000002  public_key.pem
ca-key.pem       ib_logfile0         mysql-0-bin.000003  server-cert.pem
ca.pem           ib_logfile1         mysql-0-bin.000004  server-key.pem
client-cert.pem  ibtmp1              mysql-0-bin.index   sys
client-key.pem   mysql               performance_schema
ib_buffer_pool   mysql-0-bin.000001  private_key.pem
[root@server2 mysql]# 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/
[root@server2 mysql]# kubectl exec mysql-0 -c mysql -- ls /etc/mysql/conf.d    查看容器挂载目录的内容,有两个文件
master.cnf      
server-id.cnf
[root@server2 mysql]# kubectl exec mysql-0 -c mysql  -- cat /etc/mysql/conf.d/master.cnf  查看文件具体内容
[mysqld]
log-bin    
[root@server2 mysql]# kubectl exec mysql-0 -c mysql  -- cat /etc/mysql/conf.d/server-id.cnf   查看文件具体内容
[mysqld]
server-id=100
上述master已经设置成功,该设置slave了

k8s(七)—statefullset部署mysql主从集群_第2张图片

[root@server2 mysql]# kubectl apply -f deploy.yaml   创建,删除pod
statefulset.apps/mysql configured
[root@server2 mysql]# vim deploy.yaml   
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: mysql
spec:
  selector:
    matchLabels:
      app: mysql
  serviceName: mysql
  replicas: 1   1个副本数
  template:
    metadata:
      labels:
        app: mysql
    spec:
      initContainers:
      - name: init-mysql
        image: 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
           mountPath: /mnt/config-map
      - name: clone-mysql     在科隆一个镜像xtrabackup,用于接收mysql-0的数据
        image: 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: 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: 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$( 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 "$(

k8s(七)—statefullset部署mysql主从集群_第3张图片

[root@server2 mysql]# kubectl logs mysql-1 -c init-mysql   查看初始化日志输出
++ hostname
+ [[ mysql-1 =~ -([0-9]+)$ ]]
+ ordinal=1   数字取1
+ echo '[mysqld]'
+ echo server-id=101   server-id 就是100+1
+ [[ 1 -eq 0 ]]   id不等0则拷贝slave.cnf
+ cp /mnt/config-map/slave.cnf /mnt/conf.d/   
[root@server2 mysql]# kubectl logs mysql-1 clone-mysql   查看clone日志输出
+ [[ -d /var/lib/mysql/mysql ]]
++ hostname
+ [[ mysql-1 =~ -([0-9]+)$ ]]
+ ordinal=1
+ [[ 1 -eq 0 ]]
+ ncat --recv-only mysql-0.mysql 3307  开启一个3307端口,接收mysql-0数据
+ xbstream -x -C /var/lib/mysql
+ xtrabackup --prepare --target-dir=/var/lib/mysql

查看克隆日志输出
k8s(七)—statefullset部署mysql主从集群_第4张图片
k8s(七)—statefullset部署mysql主从集群_第5张图片

[root@server2 mysql]# vim deploy.yaml 

k8s(七)—statefullset部署mysql主从集群_第6张图片
k8s(七)—statefullset部署mysql主从集群_第7张图片

[root@server2 mysql]# kubectl apply -f deploy.yaml 创建
[root@server2 mysql]# kubectl get pod   创建成功
NAME      READY   STATUS        RESTARTS      AGE
mysql-0   2/2     Terminating   0             37m
mysql-1   2/2     Running       0             101s
mysql-2   2/2     Running       1 (22s ago)   89s
[root@server2 mysql]# kubectl logs mysql-2 clone-mysql
+ [[ -d /var/lib/mysql/mysql ]]  
++ hostname
+ [[ mysql-2 =~ -([0-9]+)$ ]]
+ ordinal=2
+ [[ 2 -eq 0 ]]
+ ncat --recv-only mysql-1.mysql 3307    第2个slave是从第一个slave拿数据
+ xbstream -x -C /var/lib/mysql
+ xtrabackup --prepare --target-dir=/var/lib/mysql
[root@server2 mysql]# kubectl logs mysql-2 xtrabackup
+ cd /var/lib/mysql
+ [[ -f xtrabackup_slave_info ]]    直接获取上一个slave标志,这里面已经有之前的sql语句
+ [[ xCHANGE MASTER TO MASTER_LOG_FILE='mysql-0-bin.000005', MASTER_LOG_POS=154 != \x ]]
+ cat xtrabackup_slave_info    
+ sed -E 's/;$//g'
+ rm -f xtrabackup_slave_info xtrabackup_binlog_info   
+ [[ -f change_master_to.sql.in ]]
Initializing replication from clone position
+ mysql -h 127.0.0.1 -e 'CHANGE MASTER TO MASTER_LOG_FILE='\''mysql-0-bin.000005'\'', MASTER_LOG_POS=154,                 MASTER_HOST='\''mysql-0.mysql'\'',                 MASTER_USER='\''root'\'',                 MASTER_PASSWORD='\'''\'',                 MASTER_CONNECT_RETRY=10;               START SLAVE;'
+ mv change_master_to.sql.in change_master_to.sql.orig
+ 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'

测试:
k8s(七)—statefullset部署mysql主从集群_第8张图片
k8s(七)—statefullset部署mysql主从集群_第9张图片
k8s(七)—statefullset部署mysql主从集群_第10张图片
k8s(七)—statefullset部署mysql主从集群_第11张图片

你可能感兴趣的:(企业自动化运维实战,kubernetes)