K8S 集群上部署、管理MySql集群

一、 MySQL高可用方案

​ 本文的MySQL高可用方案为主从复制+读写分离,即由单一的master和多个slave所构成。其中,客户端通过master对数据库进行写操作,通过slave端进行读操作。master出现问题后,可以将应用切换到slave端。 此方案是MySQL官方提供的一种高可用解决方案,节点间的数据同步采用MySQL Replication技术。

​ MySQL Replication从一个MySQL数据库服务器(master)的数据复制到一个或多个MySQL数据库服务器(slave)。在默认情况下,复制是异步的;slave不需要一直接收来自主机的更新。根据配置,可以复制数据库中的所有数据库、选定的数据库,或者特定的表。

二、部署须知

三、部署步骤

3.1 设置动态PersistentVolume

官网教程也是省略了这一步,没有新建PersistentVolume配置器

(a) 新建pv1.yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  labels:
    app: mysq0
  name: data-mysql-0
spec:
  #指定pv的容量为1Gi
  capacity:
    storage: 10Gi
  #指定访问模式
  accessModes:
    #pv能以readwrite模式mount到单个节点
    - ReadWriteOnce
  hostPath:
    path: /opt/mysql0
    type: DirectoryOrCreate
  #指定pv的回收策略,即pvc资源释放后的事件.recycle(不建议,使用动态供给代替)删除pvc的所有文件
  persistentVolumeReclaimPolicy: Retain

(b) 新建pv2.yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  labels:
    app: mysql
  name: data-mysql-1
spec:
  #指定pv的容量为1Gi
  capacity:
    storage: 10Gi
  #指定访问模式
  accessModes:
    #pv能以readwrite模式mount到单个节点
    - ReadWriteOnce
  hostPath:
    path: /opt/mysql1
    type: DirectoryOrCreate
  #指定pv的回收策略,即pvc资源释放后的事件.recycle(不建议,使用动态供给代替)删除pvc的所有文件
  persistentVolumeReclaimPolicy: Retain

(c) 新建pv3.yaml

apiVersion: v1
kind: PersistentVolume
metadata:
  labels:
    app: mysql
  name: data-mysql-2
spec:
  #指定pv的容量为1Gi
  capacity:
    storage: 10Gi
  #指定访问模式
  accessModes:
    #pv能以readwrite模式mount到单个节点
    - ReadWriteOnce
  hostPath:
    path: /opt/mysql2
    type: DirectoryOrCreate
  #指定pv的回收策略,即pvc资源释放后的事件.recycle(不建议,使用动态供给代替)删除pvc的所有文件
  persistentVolumeReclaimPolicy: Retain

分别运行以上的PersistentVolume(重要,否则mysql集群会初始化失败)

kubectl create -f pv1.yaml
kubectl create -f pv2.yaml
kubectl create -f pv3.yaml

3.2 创建mysql-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
    log_bin_trust_function_creators=1
    lower_case_table_names=1
  slave.cnf: |
    # Apply this config only on slaves.
    [mysqld]
    super-read-only
    log_bin_trust_function_creators=1

3.3 创建 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

3.4 创建mysql-statefulset.yaml

​ 鉴于mysql为有状态服务,这里采用statefulset的方式部署

类型特性 Deployment StatefulSet
是否暴露到外网 可以 一般不
请求面向的对象 serviceName 指定pod的域名
灵活性 只能通过service/serviceIp访问到k8s自动转发的pod 可以访问任意一个自定义的pod
易用性 只需要关心Service的信息即可 需要知道要访问的pod启动的名称、headlessService名称
PV/PVC绑定关系的稳定性(多replicas) (pod挂掉后重启)无法保证初始的绑定关系 可以保证
pod名称稳定性 不稳定,因为是通过template创建,每次为了避免重复都会后缀一个随机数 稳定,每次都一样
启动顺序(多replicas) 随机启动,如果pod宕掉重启,会自动分配一个node重新启动 pod按 app-0、app-1...app-(n-1),如果pod宕掉重启,还会在之前的node上重新启动
停止顺序(多replicas) 随机停止 倒序停止
集群内部服务发现 只能通过service访问到随机的pod 可以打通pod之间的通信(主要是被发现)
性能开销 无需维护pod与node、pod与PVC 等关系 比deployment类型需要维护额外的关系信息

创建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: 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: ist0ne/xtrabackup
        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: ist0ne/xtrabackup
        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 <<EOF
          $(<change_master_to.sql.orig),
            MASTER_HOST='mysql-0.mysql',
            MASTER_USER='root',
            MASTER_PASSWORD='',
            MASTER_CONNECT_RETRY=10;
          START SLAVE;
          EOF
          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
      - name: mysql_exporter
        env:
        - name: DATA_SOURCE_NAME
          value: root:@(127.0.0.1:3306)/
        image: prom/mysqld-exporter
        imagePullPolicy: Always
        name: mysql-exporter
        ports: 
        - containerPort: 9104
          protocol: TCP
      volumes:
      - name: conf
        emptyDir: {}
      - name: config-map
        configMap:
          name: mysql
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 10Gi

注意事项:

  • 官方文档地址为image: gcr.io/google-samples/xtrabackup:1.0

    亲测,拉取image会失败,需要改成以下配置

# 该镜像地址无法获取,导致mysql在pod中初始化失败
image: ist0ne/xtrabackup
如果不确定可以,docker search  xtrabackup,查看一下可用的xtrabackup镜像
  • 由于要实现mysql集群的监控,故需要增加mysqld-exporter的image实现mysql集群信息的暴露。暴露端口9104。

四、MySQL集群监控

4.1简述

​ Prometheus(普罗米修斯)是一套开源的监控&报警&时间序列数据库的组合,现在最常见的Kubernetes容器管理系统中,通常会搭配Prometheus进行监控。

​ Prometheus基本原理是通过HTTP协议周期性抓取被监控组件的状态,这样做的好处是任意组件只要提供HTTP接口就可以接入监控系统,不需要任何SDK或者其他的集成过程。这样做非常适合虚拟化环境比如VM或者Docker 。

4.2 prometheus 安装部署

​ 本文采用docker安装prometheus 。

4.2.1 拉取镜像
docker pull prom/prometheus
4.2.2 修改配置文件

在本机上新建需要挂载的prometheus的配置文件,与数据存储文件

vim prometheus.yml
# 写入以下内容
# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      # - alertmanager:9093

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
    - targets: ['localhost:9090']
    # k8s中mysql的集群信息
  - job_name: 'mysql-0'
    static_configs:
      - targets: ['10.244.1.6:9104']
        labels:
          instance: db1
  - job_name: 'mysql-1'
    static_configs:
      - targets: ['10.244.2.5:9104']
        labels:
          instance: db2
  - job_name: 'mysql-2'
    static_configs:
      - targets: ['10.244.0.7:9104']
4.2.3 映射配置文件启动prometheus
docker run -d --name myPrometheus -p 9090:9090 -v /opt/mgc/myPrometheus/prometheus.yml:/etc/prometheus/prometheus.yml -v /opt/mgc/myPrometheus/prometheus-data:/prometheus-data prom/prometheus
4.2.4 访问prometheus

五、MySQL 数据备份与迁移

5.1 数据备份

​ 由于在statefulset中的mysql集群配置,采用了挂载卷的形式存储数据到本地磁盘,故已实现了mysql的数据备份。详见3.3中的mysql-statefulset.yaml配置文件

5.2 数据迁移

5.2.1 从mysql master 写入数据
kubectl run mysql-client --image=mysql:5.7 -i --rm --restart=Never --\
  mysql -h mysql-0.mysql <<EOF
CREATE DATABASE test2;
CREATE TABLE test2.messages (message VARCHAR(250));
INSERT INTO test.messages VALUES ('hello mgc');
EOF
5.2.2 从mysql slave读取数据
kubectl run mysql-client --image=mysql:5.7 -i -t --rm --restart=Never -- mysql -h mysql-read -e "SELECT * FROM test.messages"
5.2.3 查看集群状态
[root@k8s-m1 mgc]# kubectl get no
NAME     STATUS   ROLES    AGE   VERSION
k8s-m1   Ready    <none>   72d   v1.13.5
k8s-m2   Ready    <none>   72d   v1.13.5
k8s-m3   Ready    <none>   72d   v1.13.5
5.2.4 将节点k8s-m1设置为维护状态
[root@k8s-m1 mgc]# kubectl cordon k8s-m1
node/k8s-m1 cordoned
5.2.5 再次查看集群状态
[root@k8s-m1 mgc]# kubectl get no
NAME     STATUS                     ROLES    AGE   VERSION
k8s-m1   Ready,SchedulingDisabled   <none>   72d   v1.13.5
k8s-m2   Ready                      <none>   72d   v1.13.5
k8s-m3   Ready                      <none>   72d   v1.13.5

[root@k8s-m1 mgc]# kubectl get pods -owide
NAME      READY   STATUS    RESTARTS   AGE     IP           NODE     NOMINATED NODE   READINESS GATES
mysql-0   3/3     Running   0          7m52s   10.244.2.6   k8s-m3   <none>           <none>
mysql-1   3/3     Running   0          46h     10.244.2.5   k8s-m3   <none>           <none>
mysql-2   3/3     Running   0          46h     10.244.0.7   k8s-m2   <none>           <none>

5.2.6 迁移mysql-0
[root@k8s-m1 mgc]# kubectl delete pod/mysql-0
pod "mysql-0" deleted
5.2.7 验证数据
kubectl run mysql-client --image=mysql:5.7 -i --rm --restart=Never --\
mysql -h mysql-0.mysql -e "SELECT * FROM test.messages"

message
hello
5.2.8 恢复节点
kubectl uncordon k8s-m1

六、k8s常用命令

查看启动进度

kubectl get pods -l app=mysql --watch

查看pod

kubectl get pods

删除pod
kubectl delete pod pod名称
可以使用describe命令查看这个失败的Pod的明细:
$ kubectl describe pod fail-1034443984-jerry

]# kubectl create -f pv3.yaml

查看pod的详情

kubectl get pvc,pv,statefulset,pod,service,configmap |grep mysql

检查pv,pvc

[root@k8s-m1 mgc]# kubectl get pvc,pv |grep mysql

persistentvolumeclaim/data-mysql-0   Bound    data-mysql-0   10Gi       RWO                           23h
persistentvolumeclaim/data-mysql-1   Bound    data-mysql-1   10Gi       RWO                           23h
persistentvolumeclaim/data-mysql-2   Bound    data-mysql-2   10Gi       RWO                           23h
persistentvolume/data-mysql-0   10Gi       RWO            Retain           Bound    default/data-mysql-0                           23h
persistentvolume/data-mysql-1   10Gi       RWO            Retain           Bound    default/data-mysql-1                           23h
persistentvolume/data-mysql-2   10Gi       RWO            Retain           Bound    default/data-mysql-2                           23h

检查pod

[root@k8s-m1 mgc]# kubectl get po -owide
NAME      READY   STATUS    RESTARTS   AGE   IP           NODE     NOMINATED NODE   READINESS GATES
mysql-0   2/2     Running   0          23h   10.244.1.2   k8s-m1   <none>           <none>
mysql-1   2/2     Running   0          23h   10.244.2.4   k8s-m3   <none>           <none>
mysql-2   2/2     Running   0          23h   10.244.0.6   k8s-m2   <none>           <none>

https://segmentfault.com/a/1190000012244714

查看pod的状态:

可以使用describe命令查看这个失败的Pod的明细:
$ kubectl describe pod fail-1034443984-jerry

详细信息查询

kubectl get pod mysql-0 --output yaml