当前位置:   article > 正文

Kubernetes 部署 MySQL 高可用读写分离

f xtra ,

Kubernetes 部署 MySQL 高可用读写分离

简介: 在有状态应用中,MySQL是我们最常见也是最常用的。本文我们将实战部署一个一组多从的MySQL集群

832c823274320409a252303561e2dc9e.png

一、配置准备

configMap

 
 
  1. cat > mysql-configmap.yaml << EOF
  2. apiVersion: v1
  3. kind: ConfigMap
  4. metadata:
  5. name: mysql
  6. labels:
  7. app: mysql
  8. data:
  9. master.cnf: |
  10. # Apply this config only on the master.
  11. [mysqld]
  12. log-bin
  13. slave.cnf: |
  14. # Apply this config only on slaves.
  15. [mysqld]
  16. super-read-only
  17. EOF

configMap可以将配置文件和镜像解耦开。
上面的配置意思是,创建一个master.cnf文件配置内容为:log-bin,即开启bin-log日志,供主节点使用。
创建一个slave.cnf文件配置内容为:super-read-only,设为该节点只读,供备用节点使用。

service

 
 
  1. cat > mysql-services.yaml << EOF
  2. apiVersion: v1
  3. kind: Service
  4. metadata:
  5. name: mysql
  6. labels:
  7. app: mysql
  8. spec:
  9. ports:
  10. - name: mysql
  11. port: 3306
  12. clusterIP: None
  13. selector:
  14. app: mysql
  15. ---
  16. # Client service for connecting to any MySQL instance for reads.
  17. # For writes, you must instead connect to the master: mysql-0.mysql.
  18. apiVersion: v1
  19. kind: Service
  20. metadata:
  21. name: mysql-read
  22. labels:
  23. app: mysql
  24. spec:
  25. ports:
  26. - name: mysql
  27. port: 3306
  28. selector:
  29. app: mysql
  30. EOF

StatefulSet

 
 
  1. apiVersion: apps/v1
  2. kind: StatefulSet
  3. metadata:
  4. name: mysql
  5. spec:
  6. selector:
  7. matchLabels:
  8. app: mysql
  9. serviceName: mysql
  10. replicas: 3
  11. template:
  12. metadata:
  13. labels:
  14. app: mysql
  15. spec:
  16. # 设置初始化容器,进行一些准备工作
  17. initContainers:
  18. - name: init-mysql
  19. image: mysql:5.7
  20. # 为每个MySQL节点配置service-id
  21. # 如果节点序号是0,则使用master的配置, 其余节点使用slave的配置
  22. command:
  23. - bash
  24. - "-c"
  25. - |
  26. set -ex
  27. # 基于 Pod 序号生成 MySQL 服务器的 ID。
  28. [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
  29. ordinal=${BASH_REMATCH[1]}
  30. echo [mysqld] > /mnt/conf.d/server-id.cnf
  31. # 添加偏移量以避免使用 server-id=0 这一保留值。
  32. echo server-id=$((100 + $ordinal)) >> /mnt/conf.d/server-id.cnf
  33. # Copy appropriate conf.d files from config-map to emptyDir.
  34. # 将合适的 conf.d 文件从 config-map 复制到 emptyDir。
  35. if [[ $ordinal -eq 0 ]]; then
  36. cp /mnt/config-map/master.cnf /mnt/conf.d/
  37. else
  38. cp /mnt/config-map/slave.cnf /mnt/conf.d/
  39. fi
  40. volumeMounts:
  41. - name: conf
  42. mountPath: /mnt/conf.d
  43. - name: config-map
  44. mountPath: /mnt/config-map
  45. - name: clone-mysql
  46. image: registry.cn-hangzhou.aliyuncs.com/chenby/xtrabackup:1.0
  47. # 为除了节点序号为0的主节点外的其它节点,备份前一个节点的数据
  48. command:
  49. - bash
  50. - "-c"
  51. - |
  52. set -ex
  53. # 如果已有数据,则跳过克隆。
  54. [[ -d /var/lib/mysql/mysql ]] && exit 0
  55. # 跳过主实例(序号索引 0)的克隆。
  56. [[ `hostname` =~ -([0-9]+)$ ]] || exit 1
  57. ordinal=${BASH_REMATCH[1]}
  58. [[ $ordinal -eq 0 ]] && exit 0
  59. # 从原来的对等节点克隆数据。
  60. ncat --recv-only mysql-$(($ordinal-1)).mysql 3307 | xbstream -x -C /var/lib/mysql
  61. # 准备备份。
  62. xtrabackup --prepare --target-dir=/var/lib/mysql
  63. volumeMounts:
  64. - name: data
  65. mountPath: /var/lib/mysql
  66. subPath: mysql
  67. - name: conf
  68. mountPath: /etc/mysql/conf.d
  69. containers:
  70. - name: mysql
  71. image: mysql:5.7
  72. # 设置支持免密登录
  73. env:
  74. - name: MYSQL_ALLOW_EMPTY_PASSWORD
  75. value: "1"
  76. ports:
  77. - name: mysql
  78. containerPort: 3306
  79. volumeMounts:
  80. - name: data
  81. mountPath: /var/lib/mysql
  82. subPath: mysql
  83. - name: conf
  84. mountPath: /etc/mysql/conf.d
  85. resources:
  86. # 设置启动pod需要的资源,官方文档上需要500m cpu,1Gi memory。
  87. # 我本地测试的时候,会因为资源不足,报1 Insufficient cpu, 1 Insufficient memory错误,所以我改小了点
  88. requests:
  89. # m是千分之一的意思,100m表示需要0.1个cpu
  90. cpu: 1024m
  91. # Mi是兆的意思,需要100M 内存
  92. memory: 1Gi
  93. livenessProbe:
  94. # 使用mysqladmin ping命令,对MySQL节点进行探活检测
  95. # 在节点部署完30秒后开始,每10秒检测一次,超时时间为5秒
  96. exec:
  97. command: ["mysqladmin", "ping"]
  98. initialDelaySeconds: 30
  99. periodSeconds: 10
  100. timeoutSeconds: 5
  101. readinessProbe:
  102. # 对节点服务可用性进行检测, 启动5秒后开始,每2秒检测一次,超时时间1秒
  103. exec:
  104. # 检查我们是否可以通过 TCP 执行查询(skip-networking 是关闭的)。
  105. command: ["mysql", "-h", "127.0.0.1", "-e", "SELECT 1"]
  106. initialDelaySeconds: 5
  107. periodSeconds: 2
  108. timeoutSeconds: 1
  109. - name: xtrabackup
  110. image: registry.cn-hangzhou.aliyuncs.com/chenby/xtrabackup:1.0
  111. ports:
  112. - name: xtrabackup
  113. containerPort: 3307
  114. # 开始进行备份文件校验、解析和开始同步
  115. command:
  116. - bash
  117. - "-c"
  118. - |
  119. set -ex
  120. cd /var/lib/mysql
  121. # 确定克隆数据的 binlog 位置(如果有的话)。
  122. if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then
  123. # XtraBackup 已经生成了部分的 “CHANGE MASTER TO” 查询
  124. # 因为我们从一个现有副本进行克隆。(需要删除末尾的分号!)
  125. cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in
  126. # 在这里要忽略 xtrabackup_binlog_info (它是没用的)。
  127. rm -f xtrabackup_slave_info xtrabackup_binlog_info
  128. elif [[ -f xtrabackup_binlog_info ]]; then
  129. # 我们直接从主实例进行克隆。解析 binlog 位置。
  130. [[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
  131. rm -f xtrabackup_binlog_info xtrabackup_slave_info
  132. echo "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\
  133. MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.in
  134. fi
  135. # 检查我们是否需要通过启动复制来完成克隆。
  136. if [[ -f change_master_to.sql.in ]]; then
  137. echo "Waiting for mysqld to be ready (accepting connections)"
  138. until mysql -h 127.0.0.1 -e "SELECT 1"; do sleep 1; done
  139. echo "Initializing replication from clone position"
  140. mysql -h 127.0.0.1 \
  141. -e "$(<change_master_to.sql.in), \
  142. MASTER_HOST='mysql-0.mysql', \
  143. MASTER_USER='root', \
  144. MASTER_PASSWORD='', \
  145. MASTER_CONNECT_RETRY=10; \
  146. START SLAVE;" || exit 1
  147. # 如果容器重新启动,最多尝试一次。
  148. mv change_master_to.sql.in change_master_to.sql.orig
  149. fi
  150. # 当对等点请求时,启动服务器发送备份。
  151. exec ncat --listen --keep-open --send-only --max-conns=1 3307 -c \
  152. "xtrabackup --backup --slave-info --stream=xbstream --host=127.0.0.1 --user=root"
  153. volumeMounts:
  154. - name: data
  155. mountPath: /var/lib/mysql
  156. subPath: mysql
  157. - name: conf
  158. mountPath: /etc/mysql/conf.d
  159. resources:
  160. requests:
  161. cpu: 100m
  162. memory: 100Mi
  163. volumes:
  164. - name: conf
  165. emptyDir: {}
  166. - name: config-map
  167. configMap:
  168. name: mysql
  169. # 设置PVC
  170. volumeClaimTemplates:
  171. - metadata:
  172. name: data
  173. annotations:
  174. # 配置PVC使用nfs动态供给
  175. volume.beta.kubernetes.io/storage-class: nfs-storage
  176. spec:
  177. accessModes: ["ReadWriteOnce"]
  178. resources:
  179. requests:
  180. storage: 1Gi

二、创建所需资源

  1. # 创建configMap
  2. kubectl apply -f mysql-configmap.yaml
  3. # 创建service
  4. kubectl apply -f mysql-services.yaml
  5. # 创建statefulSet
  6. kubectl apply -f mysql-statefulset.yaml
  7. # 查看创建过程
  8. kubectl get pods --watch
  9. mysql-0 0/2 Pending 0 0s
  10. mysql-0 0/2 Pending 0 0s
  11. mysql-0 0/2 Init:0/2 0 0s
  12. mysql-0 0/2 Init:0/2 0 1s
  13. mysql-0 0/2 Init:1/2 0 2s
  14. mysql-0 0/2 PodInitializing 0 3s
  15. mysql-0 1/2 Running 0 4s
  16. mysql-0 2/2 Running 0 8s
  17. mysql-1 0/2 Pending 0 0s
  18. mysql-1 0/2 Pending 0 0s
  19. mysql-1 0/2 Init:0/2 0 0s
  20. mysql-1 0/2 Init:0/2 0 1s
  21. mysql-1 0/2 Init:1/2 0 1s
  22. mysql-1 0/2 PodInitializing 0 2s
  23. mysql-1 1/2 Running 0 3s
  24. mysql-1 2/2 Running 0 8s
  25. mysql-2 0/2 Pending 0 0s
  26. mysql-2 0/2 Pending 0 0s
  27. mysql-2 0/2 Init:0/2 0 0s
  28. mysql-2 0/2 Init:0/2 0 1s
  29. mysql-2 0/2 Init:1/2 0 2s
  30. mysql-2 0/2 PodInitializing 0 3s
  31. mysql-2 1/2 Running 0 4s
  32. mysql-2 2/2 Running 0 9s

三、测试主库

进入pod进行操作

  1. # 进入到pod mysql-0中,进行测试
  2. kubectl exec -it mysql-0 bash
  3. # 用mysql-client链接mysql-0
  4. mysql -h mysql-0
  5. Welcome to the MySQL monitor. Commands end with ; or \g.
  6. Your MySQL connection id is 276
  7. Server version: 5.7.38-log MySQL Community Server (GPL)
  8. Copyright (c) 2000, 2022, Oracle and/or its affiliates.
  9. Oracle is a registered trademark of Oracle Corporation and/or its
  10. affiliates. Other names may be trademarks of their respective
  11. owners.
  12. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  13. mysql>

创建库、表

  1. # 创建数据库test
  2. mysql> create database cby;
  3. Query OK, 1 row affected (0.00 sec)
  4. # 使用test库
  5. mysql> use cby;
  6. Database changed
  7. # 创建message表
  8. mysql> create table message (message varchar(50));
  9. Query OK, 0 rows affected (0.01 sec)
  10. # 查看message表结构
  11. mysql> show create table message;
  12. +---------+------------------------------------------------------------------------------------------------------+
  13. | Table | Create Table |
  14. +---------+------------------------------------------------------------------------------------------------------+
  15. | message | CREATE TABLE `message` (
  16. `message` varchar(50) DEFAULT NULL
  17. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
  18. +---------+------------------------------------------------------------------------------------------------------+
  19. 1 row in set (0.00 sec)

插入数据

  1. # 插入
  2. mysql> insert into message value("hello chenby");
  3. Query OK, 1 row affected (0.00 sec)
  4. # 查看
  5. mysql> select * from message;
  6. +---------------+
  7. | message |
  8. +---------------+
  9. | hello chenby |
  10. +---------------+
  11. 1 row in set (0.00 sec)

四、测试备库

连接mysql-1

 
 
  1. mysql -h mysql-1.mysql
  2. Welcome to the MySQL monitor. Commands end with ; or \g.
  3. Your MySQL connection id is 362
  4. Server version: 5.7.38 MySQL Community Server (GPL)
  5. Copyright (c) 2000, 2022, Oracle and/or its affiliates.
  6. Oracle is a registered trademark of Oracle Corporation and/or its
  7. affiliates. Other names may be trademarks of their respective
  8. owners.
  9. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  10. mysql>
  11. mysql>

查看库、表结构

  1. # 查看数据库列表
  2. mysql> show databases;
  3. +------------------------+
  4. | Database |
  5. +------------------------+
  6. | information_schema |
  7. | cby |
  8. | mysql |
  9. | performance_schema |
  10. | sys |
  11. | test |
  12. | xtrabackup_backupfiles |
  13. +------------------------+
  14. 7 rows in set (0.01 sec)
  15. # 使用cby库
  16. mysql> use cby;
  17. Reading table information for completion of table and column names
  18. You can turn off this feature to get a quicker startup with -A
  19. Database changed
  20. mysql>
  21. # 查看表列表
  22. mysql> show tables;
  23. +---------------+
  24. | Tables_in_cby |
  25. +---------------+
  26. | message |
  27. +---------------+
  28. 1 row in set (0.00 sec)
  29. # 查看message表结构
  30. mysql> show create table message;
  31. +---------+------------------------------------------------------------------------------------------------------+
  32. | Table | Create Table |
  33. +---------+------------------------------------------------------------------------------------------------------+
  34. | message | CREATE TABLE `message` (
  35. `message` varchar(50) DEFAULT NULL
  36. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
  37. +---------+------------------------------------------------------------------------------------------------------+
  38. 1 row in set (0.00 sec)
  39. mysql>
  40. # 查询数据
  41. mysql> select * from message;
  42. +---------------+
  43. | message |
  44. +---------------+
  45. | hello chenby |
  46. +---------------+
  47. 1 row in set (0.00 sec)
  48. mysql>
  49. # 写入数据
  50. mysql> insert into message values("hello world");
  51. ERROR 1290 (HY000): The MySQL server is running with the --super-read-only option so it cannot execute this statement
  52. mysql>
  53. # 这是因为mysql-1是一个只读备库,无法进行写操作。

五、测试mysql-read服务

循环中运行 SELECT @@server_id

 
 
  1. kubectl run mysql-client-loop --image=mysql:5.7 -i -t --rm --restart=Never -- bash -ic "while sleep 1; do mysql -h mysql-read -e 'SELECT @@server_id,NOW()'; done"
  2. If you don't see a command prompt, try pressing enter.
  3. +-------------+---------------------+
  4. | @@server_id | NOW() |
  5. +-------------+---------------------+
  6. | 102 | 2022-06-07 09:52:19 |
  7. +-------------+---------------------+
  8. +-------------+---------------------+
  9. | @@server_id | NOW() |
  10. +-------------+---------------------+
  11. | 101 | 2022-06-07 09:52:20 |
  12. +-------------+---------------------+
  13. +-------------+---------------------+
  14. | @@server_id | NOW() |
  15. +-------------+---------------------+
  16. | 100 | 2022-06-07 09:52:21 |
  17. +-------------+---------------------+

六、扩缩容

  1. # 扩容至5副本
  2. kubectl scale statefulset mysql --replicas=5
  3. # 查看扩容过程
  4. kubectl get pods --watch
  5. mysql-3 0/2 Pending 0 0s
  6. mysql-3 0/2 Pending 0 1s
  7. mysql-3 0/2 Pending 0 2s
  8. mysql-3 0/2 Init:0/2 0 2s
  9. mysql-3 0/2 Init:0/2 0 2s
  10. mysql-3 0/2 Init:0/2 0 3s
  11. mysql-3 0/2 Init:1/2 0 4s
  12. mysql-3 0/2 Init:1/2 0 5s
  13. mysql-3 0/2 PodInitializing 0 12s
  14. mysql-3 1/2 Error 0 13s
  15. mysql-3 1/2 Running 1 (2s ago) 14s
  16. mysql-3 2/2 Running 1 (6s ago) 18s
  17. mysql-4 0/2 Pending 0 0s
  18. mysql-4 0/2 Pending 0 0s
  19. mysql-4 0/2 Pending 0 2s
  20. mysql-4 0/2 Init:0/2 0 2s
  21. mysql-4 0/2 Init:0/2 0 2s
  22. mysql-4 0/2 Init:1/2 0 3s
  23. mysql-4 0/2 Init:1/2 0 4s
  24. mysql-4 0/2 PodInitializing 0 12s
  25. mysql-4 1/2 Error 0 13s
  26. mysql-4 1/2 Running 1 (1s ago) 14s
  27. mysql-4 2/2 Running 1 (7s ago) 20s
  28. # 缩容只2副本
  29. kubectl scale statefulset mysql --replicas=2
  30. # 查看缩容过程
  31. kubectl get pods --watch
  32. mysql-4 2/2 Terminating 1 (74s ago) 87s
  33. mysql-4 2/2 Terminating 1 (104s ago) 117s
  34. mysql-4 0/2 Terminating 1 118s
  35. mysql-4 0/2 Terminating 1 118s
  36. mysql-4 0/2 Terminating 1 118s
  37. mysql-3 2/2 Terminating 1 (2m4s ago) 2m16s
  38. mysql-3 2/2 Terminating 1 (2m34s ago) 2m46s
  39. mysql-3 0/2 Terminating 1 2m47s
  40. mysql-3 0/2 Terminating 1 2m47s
  41. mysql-3 0/2 Terminating 1 2m47s
  42. mysql-2 2/2 Terminating 0 16m
  43. mysql-2 2/2 Terminating 0 16m
  44. mysql-2 0/2 Terminating 0 16m
  45. mysql-2 0/2 Terminating 0 16m
  46. mysql-2 0/2 Terminating 0 16m

https://www.oiox.cn/  
https://www.chenby.cn/  
https://cby-chen.github.io/  
https://blog.csdn.net/qq_33921750  
https://my.oschina.net/u/3981543  
https://www.zhihu.com/people/chen-bu-yun-2  
https://segmentfault.com/u/hppyvyv6/articles  
https://juejin.cn/user/3315782802482007  
https://cloud.tencent.com/developer/column/93230  
https://www.jianshu.com/u/0f894314ae2c  
https://www.toutiao.com/c/user/token/MS4wLjABAAAAeqOrhjsoRZSj7iBJbjLJyMwYT5D0mLOgCoo4pEmpr4A/

CSDN、GitHub、知乎、开源中国、思否、掘金、简书、腾讯云、今日头条、个人博客、全网可搜《小陈运维》

文章主要发布于微信公众号:《Linux运维交流社区》

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/578905
推荐阅读
相关标签
  

闽ICP备14008679号