【全网最全最详细】Kubernetes部署Mysql主从复制+读写分离

1.前提:起码得有个已经可以部署简单pod的k8s单机或集群,每个节点必须有nfs-utils 的rpm包
PS: 本文使用静态存储卷实现,非使用存储类
2.制作拉取gcr.io镜像源脚本并拉取镜像

[root@k8s-m~ ]# cat /usr/local/bin/pull-google.com.sh
image=$1
echo $1
img=`echo $image | sed 's/k8s\.gcr\.io/anjia0532\/google-containers/g;s/gcr\.io/anjia0532/g;s/\//\./g;s/ /\n/g;s/_/-/g;s/anjia0532\./anjia0532\//g' | uniq | awk '{print ""$1""}'`
echo "docker pull $img"
docker pull $img
echo  "docker tag $img $image"
docker tag $img $image
[root@k8s-m~ ]# chmod +x /usr/local/bin/pull-google.com.sh
[root@k8s-m~ ]# pull-google.com.sh gcr.io/google-samples/xtrabackup:1.0

3.准备NFS服务,查看NFS服务器IP为192.168.1.11,准备三个持久化磁盘

[root@m-nfs~]# yum install nfs-utils
[root@m-nfs~]# mkdir -p /net/mysql-0 /net/mysql-1 /net/mysql-2
[root@m-nfs~]# ifconfig | head -2| tail -1|awk '{print $2}'
192.168.1.11 # 查看nfs服务器IP
[root@m-nfs~]# echo '/net/mysql-0 *(rw,no_root_squash)' >> /etc/exports
[root@m-nfs~]# echo '/net/mysql-1 *(rw,no_root_squash)' >> /etc/exports
[root@m-nfs~]# echo '/net/mysql-2 *(rw,no_root_squash)' >> /etc/exports
[root@m-nfs~]# systemctl restart nfs-server
[root@m-nfs~]# showmount -e 本机IP # 验证

4.创建三个持久卷(mysql-0、mysql-1、mysql-2)

  apiVersion: v1
  kind: PersistentVolume
  metadata:
    name: pv-a|pv-b|pv-c
  spec:
    capacity:
      storage: 1Gi
    accessModes: 
    - ReadWriteOnce
    - ReadOnlyMany
   #persistentVolumeReclaimPolicy: Retain # 当声明被释放,pv将保留(不清理和删除)
    persistentVolumeReclaimPolicy: Recycle # 当声明被释放,空间将回收再利用
    nfs:
      server: 192.168.1.11
      path: /net/mysql-0 | /net/mysql-1 | /net/mysql-2

5.创建configMap配置字典

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

6.部署headless服务,有状态服务都需要,让服务旗下的Pod彼此发现

apiVersion: v1
kind: Service
metadata:
  name: mysql
  labels:
    app: mysql
spec:
  ports:
  - name: mysql
    port: 3306
  clusterIP: None
  selector:
    app: mysql

7. 部署SatefulSet应用

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
        imagePullPolicy: IfNotPresent
        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: gcr.io/google-samples/xtrabackup:1.0
        imagePullPolicy: IfNotPresent
        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
        imagePullPolicy: IfNotPresent
        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: 50m
            memory: 50Mi
        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: gcr.io/google-samples/xtrabackup:1.0
        imagePullPolicy: IfNotPresent
        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 ]]; then
            # XtraBackup already generated a partial "CHANGE MASTER TO" query
            # because we're cloning from an existing slave.
            mv xtrabackup_slave_info change_master_to.sql.in
            # Ignore xtrabackup_binlog_info in this case (it's useless).
            rm -f 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 xtrabackup_binlog_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"
            # In case of container restart, attempt this at-most-once.
            mv change_master_to.sql.in change_master_to.sql.orig
            mysql -h 127.0.0.1 <
        volumeMounts:
        - name: data
          mountPath: /var/lib/mysql
          subPath: mysql
        - name: conf
          mountPath: /etc/mysql/conf.d
        resources:
          requests:
            cpu: 10m
            memory: 10Mi
      volumes:
      - name: conf
        emptyDir: {}
      - name: config-map
        configMap:
          name: mysql
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 0.1Gi

8.查看状态

[root@k8s-master ~]# kubectl get all | grep mysql

pod/mysql-0                         2/2     Running   0          6h
pod/mysql-1                         2/2     Running   1          5h23m
pod/mysql-2                         2/2     Running   0          4h21m
statefulset.apps/mysql   3/3     6h

9.测试数据同步看这篇 简书
(1).依次进入mysql-2,mysql-1,mysql-0三个容器执行创建数据demo
(2).往mysql-0创建表,并插入数据

CREATE TABLE demo.messages (message VARCHAR(250)); 
INSERT INTO demo.messages VALUES ('hello');

(3).进入三个数据库进行读服务

select * from demo.message;

10. 部署对外读服务

apiVersion: v1
kind: Service
metadata:
  name: mysql-read
  labels:
    app: mysql
spec:
  ports:
  - name: mysql
    port: 3306
    targetPort: 3306
    nodePort: 30036
  type: NodePort
  selector:
    app: mysql

11.部署对外读写服务

[root@k8s-master ~]# kubectl get pods --show-labels | grep mysql-0 | awk '{print $6}' | awk -F, '{print $3}'
statefulset.kubernetes.io/pod-name=mysql-0 

得到该标签后写入如下selector字段

apiVersion: v1
kind: Service
metadata:
  name: mysql-writeandread
  labels:
    app: mysql
spec:
  ports:
  - name: mysql
    port: 3306
    targetPort: 3306
    nodePort: 30006
  selector:
    statefulset.kubernetes.io/pod-name: mysql-0
  type: NodePort

12. 使用集群任意节点IP:nodePort进行连接
附加篇.【深入分析】K8s部署Mysql主从复制+读写分离

你可能感兴趣的:(Kubernetes)