kubernetes搭建mysql集群服务

本文涉及的产品
云数据库 RDS SQL Server,独享型 2核4GB
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介:

参考链接:https://kubernetes.io/docs/tasks/run-application/run-replicated-stateful-application/

一、创建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

在pod初始化时, pod会根据自身标识(master或slave)从configmap中应用指定配置. 被应用配置将覆盖my.cnf中的配置. 目的是使master向slave提供复制日志服务,并设置slave拒绝非复制写入.

二、创建headless service

# 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

三、创建StatefulSet

apiVersion: apps/v1beta1
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: gcr.io/google-samples/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_ROOT_PASSWORD
          value: "123",
        - name: MYSQL_REPLICATION_USER
          value: "sync",
        - name: MYSQL_REPLICATION_PASSWORD
          value: "sync",
        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", "-uroot", "-p123", "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", "-uroot", "-p123", "-e", "SELECT 1"]
          initialDelaySeconds: 5
          periodSeconds: 2
          timeoutSeconds: 1
      - name: xtrabackup
        image: gcr.io/google-samples/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 ]]; 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 -uroot -p123 -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 -uroot -p123  <<EOF
          $(<change_master_to.sql.orig),
            MASTER_HOST='mysql-0.mysql',
            MASTER_USER='root',
            MASTER_PASSWORD='123',
            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 --password=123"
        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

这里使用了两个初始化容器.
第一个初始化容器init-mysql作用包括根据pod名称后缀生成server_id文件, 从configmap中获取指定配置. 这里默认StatefulSet控制的第一个pod即mysql-0为master, 其余为slave.
第二个clone-mysql使用开源工具xtrabackup, 用于当前slave从前一个slave复制数据, 当有新的作为slave的pod加入集群时, 这个pod会从上一个pod(序号小1)的非master的pod复制数据, 因为新pod加入时, 我们必须假定master中的数据是不为空的, 需要进行一次复制操作, 这样在扩容时会避免数据丢失,
而从前一个pod复制数据是因为StatefulSet按顺序启动, 当前一个pod为ready时才启动后一个pod的机制而来.

当init容器执行完成后, 常规容器开始启动并运行. mysql Pods由运行mysqld服务的mysql容器和充当SideCar的xtrabackup容器组成(挎斗模式解析请见http://www.mamicode.com/info-detail-2149700.html)。

四、创建用于访问Service

# 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-access
  labels:
    app: mysql
spec:
  ports:
  - name: mysql
    port: 3306
  selector:
    app: mysql

五、查看

root@node4:~# kubectl -n admin-d2069c get pvc,pv,statefulset,pod,service,configmap |grep mysql
pvc/storage-mysql-0                    Bound     pvc-bb591208-c2f4-11e8-b599-0050568eef9f   512M       RWX            managed-nfs-storage   12m
pvc/storage-mysql-1                    Bound     pvc-c4ada169-c2f4-11e8-b599-0050568eef9f   512M       RWX            managed-nfs-storage   12m
pvc/storage-mysql-2                    Bound     pvc-ce20ad71-c2f4-11e8-b599-0050568eef9f   512M       RWX            managed-nfs-storage   11m

pv/pvc-bb591208-c2f4-11e8-b599-0050568eef9f   512M       RWX            Delete           Bound     admin-d2069c/storage-mysql-0                   managed-nfs-storage             12m
pv/pvc-c4ada169-c2f4-11e8-b599-0050568eef9f   512M       RWX            Delete           Bound     admin-d2069c/storage-mysql-1                   managed-nfs-storage             12m
pv/pvc-ce20ad71-c2f4-11e8-b599-0050568eef9f   512M       RWX            Delete           Bound     admin-d2069c/storage-mysql-2                   managed-nfs-storage             11m

statefulsets/mysql                      3         3         12m

po/mysql-0                                   2/2       Running    0          12m
po/mysql-1                                   2/2       Running    0          12m
po/mysql-2                                   2/2       Running    0          11m

svc/mysql                       ClusterIP   None            <none>        3306/TCP                          12m
svc/mysql-access                ClusterIP   10.68.8.223     <none>        3306/TCP                          12m

cm/mysql                      2         12m

六、测试集群

登录mysql-0, 执行

 kubectl -n admin-d2069c exec -it mysql-0 /bin/bash

进入mysql-0后连接mysql:

mysql -p123

创建database, 并以同样方式登录mysql-1或mysql-2, 发现其下已经将新创建的database同步则为验证成功.

相关实践学习
容器服务Serverless版ACK Serverless 快速入门:在线魔方应用部署和监控
通过本实验,您将了解到容器服务Serverless版ACK Serverless 的基本产品能力,即可以实现快速部署一个在线魔方应用,并借助阿里云容器服务成熟的产品生态,实现在线应用的企业级监控,提升应用稳定性。
云原生实践公开课
课程大纲 开篇:如何学习并实践云原生技术 基础篇: 5 步上手 Kubernetes 进阶篇:生产环境下的 K8s 实践 相关的阿里云产品:容器服务&nbsp;ACK 容器服务&nbsp;Kubernetes&nbsp;版(简称&nbsp;ACK)提供高性能可伸缩的容器应用管理能力,支持企业级容器化应用的全生命周期管理。整合阿里云虚拟化、存储、网络和安全能力,打造云端最佳容器化应用运行环境。 了解产品详情:&nbsp;https://www.aliyun.com/product/kubernetes
目录
相关文章
|
4天前
|
Kubernetes Ubuntu 应用服务中间件
在Ubuntu22.04 LTS上搭建Kubernetes集群
在Ubuntu22.04.4上安装Kubernetes v1.28.7,步骤超详细
44 1
在Ubuntu22.04 LTS上搭建Kubernetes集群
|
22天前
|
监控 安全 关系型数据库
在规划阿里云RDS跨区迁移资源和服务可用性
在规划阿里云RDS跨区迁移资源和服务可用性
206 4
|
26天前
|
Kubernetes 安全 Docker
在 K8s 集群中创建 DERP 服务器
在 K8s 集群中创建 DERP 服务器
|
26天前
|
Kubernetes 安全 Docker
如何在 K8S 集群范围使用 imagePullSecret?
如何在 K8S 集群范围使用 imagePullSecret?
|
26天前
|
Prometheus 监控 Kubernetes
如何用 Prometheus Operator 监控 K8s 集群外服务?
如何用 Prometheus Operator 监控 K8s 集群外服务?
|
26天前
|
Prometheus 监控 Kubernetes
监控 Kubernetes 集群证书过期时间的三种方案
监控 Kubernetes 集群证书过期时间的三种方案
|
9天前
|
Kubernetes 调度 Docker
玩转Kubernetes—使用minikube操作集群
玩转Kubernetes—使用minikube操作集群
34 0
|
9天前
|
Kubernetes Ubuntu Linux
玩转Kubernetes—尝试以不同方式初始化集群
玩转Kubernetes—尝试以不同方式初始化集群
24 0
|
19天前
|
存储 关系型数据库 数据库
在进行RDS(Amazon Relational Database Service,亚马逊关系数据库服务)迁移时,兼容性审查
在进行RDS(Amazon Relational Database Service,亚马逊关系数据库服务)迁移时,兼容性审查
15 1
|
23天前
|
监控 负载均衡 关系型数据库
MySQL技能完整学习列表13、MySQL高级特性——1、分区表(Partitioning)——2、复制(Replication)——3、集群(Clustering)
MySQL技能完整学习列表13、MySQL高级特性——1、分区表(Partitioning)——2、复制(Replication)——3、集群(Clustering)
38 0

推荐镜像

更多