K8S部署MySQL5.7的主从服务

mysql-slave-0是master
mysql-slave-1是slave
当mysql写的时候,找headless service中的 mysql-slave-0.mysql57-slave-headless;当mysql读的时候,找clusterip service中的mysql57-slave-read读,实现读写分离。
statefulset维护两个副本,一个主一个从
因为主从的配置不同所以通过configmap来解决主从配置不同的问题

创建命名空间

cat mysql-cluster-s.yaml

apiVersion: v1
kind: Namespace
metadata:name: mysql-cluster
 创建配置文件

这一配置不适合生产环境。 MySQL 设置都使用的是不安全的默认值,这是因为我们想把重点放在 Kubernetes 中运行有状态应用程序的一般模式上。

# cat configmap.yaml 
apiVersion: v1
kind: ConfigMap
metadata:name: mysql57-slave-cfgnamespace: mysql-clusterlabels:app: mysql57-slave
data:master.cnf: |# Apply this config only on the master.[mysqld]log-bin  # 主mysql激活二进制日志slave.cnf: |# Apply this config only on slaves.[mysqld]super-read-only   # 从mysql上面设置为只读
创建service服务

 cat service.yaml 

为 StatefulSet 成员提供稳定的 DNS 表项的无头服务(Headless Service)

apiVersion: v1
kind: Service
metadata:name: mysql57-slave-headlessnamespace: mysql-clusterlabels:app: mysql57-slave
spec:ports:- name: mysqlport: 3306clusterIP: Noneselector:app: mysql57-slave
---
# 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: mysql57-slave-readnamespace: mysql-clusterlabels:app: mysql57-slave
spec:ports:- name: mysqlport: 3306selector:app: mysql57-slave
 创建sts服务
apiVersion: apps/v1
kind: StatefulSet
metadata:name: mysql57-slavenamespace: mysql-cluster
spec:selector:matchLabels:app: mysql57-slaveserviceName: mysql57-slave-headlessreplicas: 2template:metadata:labels:app: mysql57-slavespec:initContainers:- name: init-mysqlimage: mysql:5.7#image: mysql:8.0.36command:- bash- "-c"- |set -ex# Generate mysql server-id from pod ordinal index.[[ `tail -n 1 /etc/hosts` =~ -([0-9]+)$ ]] || exit 1#[[ `hostid` =~ -([0-9]+)$ ]] || exit 1ordinal=${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 ]]; thencp /mnt/config-map/master.cnf /mnt/conf.d/elsecp /mnt/config-map/slave.cnf /mnt/conf.d/fivolumeMounts:- name: confmountPath: /mnt/conf.d- name: config-mapmountPath: /mnt/config-map- name: clone-mysql#image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/xtrabackup:1.0# 该镜像通过附件下载xtrabackup:1.0image: gcr.io/google-samples/xtrabackup:1.0command:- 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).[[ `tail -n 1 /etc/hosts` =~ -([0-9]+)$ ]] || exit 1#[[ `hostid` =~ -([0-9]+)$ ]] || exit 1ordinal=${BASH_REMATCH[1]}[[ $ordinal -eq 0 ]] && exit 0# Clone data from previous peer.# mysql-$(($ordinal-1)).mysql->mysql57-slave-0.mysql57-slave-headlessncat --recv-only mysql57-slave-$(($ordinal-1)).mysql57-slave-headless 3307 | xbstream -x -C /var/lib/mysql# Prepare the backup.xtrabackup --prepare --target-dir=/var/lib/mysqlvolumeMounts:- name: datamountPath: /var/lib/mysqlsubPath: mysql- name: confmountPath: /etc/mysql/conf.dcontainers:- name: mysqlimage: mysql:5.7env:- name: MYSQL_ALLOW_EMPTY_PASSWORDvalue: "1"ports:- name: mysqlcontainerPort: 3306volumeMounts:- name: datamountPath: /var/lib/mysqlsubPath: mysql- name: confmountPath: /etc/mysql/conf.dresources:requests:cpu: 500mmemory: 500MilivenessProbe:exec:command: ["mysqladmin", "ping"]initialDelaySeconds: 30periodSeconds: 10timeoutSeconds: 5readinessProbe:exec:# Check we can execute queries over TCP (skip-networking is off).command: ["mysql", "-h", "127.0.0.1", "-e", "SELECT 1"]initialDelaySeconds: 5periodSeconds: 2timeoutSeconds: 1- name: xtrabackup#image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/xtrabackup:1.0#该镜像通过附件下载导入image: gcr.io/google-samples/xtrabackup:1.0ports:- name: xtrabackupcontainerPort: 3307command:- bash- "-c"- |set -excd /var/lib/mysql# Determine binlog position of cloned data, if any.if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then# XtraBackup already generated a partial "CHANGE MASTER TO" query# because we're cloning from an existing slave. (Need to remove the tailing semicolon!)cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in# Ignore xtrabackup_binlog_info in this case (it's useless).rm -f xtrabackup_slave_info xtrabackup_binlog_infoelif [[ -f xtrabackup_binlog_info ]]; then# We're cloning directly from master. Parse binlog position.[[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1rm -f xtrabackup_binlog_info xtrabackup_slave_infoecho "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.infi# Check if we need to complete a clone by starting replication.if [[ -f change_master_to.sql.in ]]; thenecho "Waiting for mysqld to be ready (accepting connections)"until mysql -h 127.0.0.1 -e "SELECT 1"; do sleep 1; doneecho "Initializing replication from clone position"## 修改名字mysql-$(($ordinal-1)).mysql->mysql57-slave-0.mysql57-slave-headlessmysql -h 127.0.0.1 -e "$(<change_master_to.sql.in), MASTER_HOST='mysql57-slave-0.mysql57-slave-headless', MASTER_USER='root', MASTER_PASSWORD='',MASTER_CONNECT_RETRY=10; START SLAVE;" || exit 1# In case of container restart, attempt this at-most-once.mv change_master_to.sql.in change_master_to.sql.origfi# 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: datamountPath: /var/lib/mysqlsubPath: mysql- name: confmountPath: /etc/mysql/conf.dresources:requests:cpu: 100mmemory: 100Mivolumes:- name: confemptyDir: {}- name: config-mapconfigMap:name: mysql57-slave-cfgvolumeClaimTemplates:- metadata:name: dataspec:accessModes: ["ReadWriteOnce"]#存储类storageClassName: longhornresources:requests:storage: 200Gi
查看mysql的主从状态是否正常

show slave status\G;

完整的yaml文件如下

apiVersion: v1
kind: Namespace
metadata:name: mysql-cluster
---
# cat configmap.yaml 
apiVersion: v1
kind: ConfigMap
metadata:name: mysql57-slave-cfgnamespace: mysql-clusterlabels:app: mysql57-slave
data:master.cnf: |# Apply this config only on the master.[mysqld]log-bin  # 主mysql激活二进制日志slave.cnf: |# Apply this config only on slaves.[mysqld]super-read-only   # 从mysql上面设置为只读
---
# cat service.yaml 
apiVersion: v1
kind: Service
metadata:name: mysql57-slave-headlessnamespace: mysql-clusterlabels:app: mysql57-slave
spec:ports:- name: mysqlport: 3306clusterIP: Noneselector:app: mysql57-slave
---
# 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: mysql57-slave-readnamespace: mysql-clusterlabels:app: mysql57-slave
spec:ports:- name: mysqlport: 3306selector:app: mysql57-slave
---
# cat statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:name: mysql57-slavenamespace: mysql-cluster
spec:selector:matchLabels:app: mysql57-slaveserviceName: mysql57-slave-headlessreplicas: 2template:metadata:labels:app: mysql57-slavespec:initContainers:- name: init-mysqlimage: mysql:5.7#image: mysql:8.0.36command:- bash- "-c"- |set -ex# Generate mysql server-id from pod ordinal index.[[ `tail -n 1 /etc/hosts` =~ -([0-9]+)$ ]] || exit 1#[[ `hostid` =~ -([0-9]+)$ ]] || exit 1ordinal=${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 ]]; thencp /mnt/config-map/master.cnf /mnt/conf.d/elsecp /mnt/config-map/slave.cnf /mnt/conf.d/fivolumeMounts:- name: confmountPath: /mnt/conf.d- name: config-mapmountPath: /mnt/config-map- name: clone-mysql#image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/xtrabackup:1.0# 该镜像通过附件下载xtrabackup:1.0image: gcr.io/google-samples/xtrabackup:1.0command:- 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).[[ `tail -n 1 /etc/hosts` =~ -([0-9]+)$ ]] || exit 1#[[ `hostid` =~ -([0-9]+)$ ]] || exit 1ordinal=${BASH_REMATCH[1]}[[ $ordinal -eq 0 ]] && exit 0# Clone data from previous peer.# mysql-$(($ordinal-1)).mysql->mysql57-slave-0.mysql57-slave-headlessncat --recv-only mysql57-slave-$(($ordinal-1)).mysql57-slave-headless 3307 | xbstream -x -C /var/lib/mysql# Prepare the backup.xtrabackup --prepare --target-dir=/var/lib/mysqlvolumeMounts:- name: datamountPath: /var/lib/mysqlsubPath: mysql- name: confmountPath: /etc/mysql/conf.dcontainers:- name: mysqlimage: mysql:5.7env:- name: MYSQL_ALLOW_EMPTY_PASSWORDvalue: "1"ports:- name: mysqlcontainerPort: 3306volumeMounts:- name: datamountPath: /var/lib/mysqlsubPath: mysql- name: confmountPath: /etc/mysql/conf.dresources:requests:cpu: 500mmemory: 500MilivenessProbe:exec:command: ["mysqladmin", "ping"]initialDelaySeconds: 30periodSeconds: 10timeoutSeconds: 5readinessProbe:exec:# Check we can execute queries over TCP (skip-networking is off).command: ["mysql", "-h", "127.0.0.1", "-e", "SELECT 1"]initialDelaySeconds: 5periodSeconds: 2timeoutSeconds: 1- name: xtrabackup#image: registry.cn-hangzhou.aliyuncs.com/hxpdocker/xtrabackup:1.0#该镜像通过附件下载导入image: gcr.io/google-samples/xtrabackup:1.0ports:- name: xtrabackupcontainerPort: 3307command:- bash- "-c"- |set -excd /var/lib/mysql# Determine binlog position of cloned data, if any.if [[ -f xtrabackup_slave_info && "x$(<xtrabackup_slave_info)" != "x" ]]; then# XtraBackup already generated a partial "CHANGE MASTER TO" query# because we're cloning from an existing slave. (Need to remove the tailing semicolon!)cat xtrabackup_slave_info | sed -E 's/;$//g' > change_master_to.sql.in# Ignore xtrabackup_binlog_info in this case (it's useless).rm -f xtrabackup_slave_info xtrabackup_binlog_infoelif [[ -f xtrabackup_binlog_info ]]; then# We're cloning directly from master. Parse binlog position.[[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1rm -f xtrabackup_binlog_info xtrabackup_slave_infoecho "CHANGE MASTER TO MASTER_LOG_FILE='${BASH_REMATCH[1]}',\MASTER_LOG_POS=${BASH_REMATCH[2]}" > change_master_to.sql.infi# Check if we need to complete a clone by starting replication.if [[ -f change_master_to.sql.in ]]; thenecho "Waiting for mysqld to be ready (accepting connections)"until mysql -h 127.0.0.1 -e "SELECT 1"; do sleep 1; doneecho "Initializing replication from clone position"## 修改名字mysql-$(($ordinal-1)).mysql->mysql57-slave-0.mysql57-slave-headlessmysql -h 127.0.0.1 -e "$(<change_master_to.sql.in), MASTER_HOST='mysql57-slave-0.mysql57-slave-headless', MASTER_USER='root', MASTER_PASSWORD='',MASTER_CONNECT_RETRY=10; START SLAVE;" || exit 1# In case of container restart, attempt this at-most-once.mv change_master_to.sql.in change_master_to.sql.origfi# 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: datamountPath: /var/lib/mysqlsubPath: mysql- name: confmountPath: /etc/mysql/conf.dresources:requests:cpu: 100mmemory: 100Mivolumes:- name: confemptyDir: {}- name: config-mapconfigMap:name: mysql57-slave-cfgvolumeClaimTemplates:- metadata:name: dataspec:accessModes: ["ReadWriteOnce"]#存储类storageClassName: longhornresources:requests:storage: 200Gi

参考链接:

https://kubernetes.io/zh-cn/docs/tasks/run-application/run-replicated-stateful-application/

https://blog.51cto.com/u_13045706/10035400

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/410028.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux操作系统常见面试题

前言 作者&#xff1a;小蜗牛向前冲 名言&#xff1a;我可以接受失败&#xff0c;但我不能接受放弃 如果觉的博主的文章还不错的话&#xff0c;还请点赞&#xff0c;收藏&#xff0c;关注&#x1f440;支持博主。如果发现有问题的地方欢迎❀大家在评论区指正 分享常见的操作系统…

原创~尚未发表!基于改进秃鹰算法的多区域微网经济优化调度程序代码!

前言 随着光伏、风电等分布式电源的发展&#xff0c;配电网的供电模式得以改变&#xff0c;解决了传统火力发电带来的能源匮乏及环境污染问题&#xff0c;但其发电的随机性及波动性对配电网的稳定运行造成一定影响。以多个微电网组成的微电网群可有效消纳分布式电源&#xff0…

Anthropic公开Claude AI系统提示词

&#x1f989; AI新闻 &#x1f680; Anthropic公开Claude AI系统提示词 摘要&#xff1a;Anthropic公司近日公开了Claude AI模型的系统提示词&#xff0c;旨在提高AI模型对人类指令的理解。系统提示词设定了对话背景和行为规则&#xff0c;通常是为了防止模型出现不良行为。…

Python数据分析利器之groupby和pivot_table使用详解

概要 在数据分析的过程中,数据聚合与数据透视是两项非常重要的操作。Python的Pandas库提供了强大的工具——groupby和pivot_table,帮助我们高效地进行数据聚合和透视分析。本文将详细介绍如何使用这两个功能,并结合示例代码展示它们的实际应用,帮助更好地掌握数据分析的技…

PTA团体程序设计天梯赛

这次题目出得比前几次简单很多&#xff0c;但有几道题占用的时间太多&#xff0c;导致后面几题仓促写完&#xff0c;未能全部正确&#xff0c;还是得多练 目录 L1-2 九牛一毛 L1-3 小孩子才做选择&#xff0c;大人全都要 L1-5 试试手气 L1-6 打PTA L1-8 随机输一次 L2-…

C++ 类和对象 3

构造函数扩展 构造函数体内的赋值&#xff1a;构造函数一般是用于类对象的初始化的&#xff0c;但严谨来说并不是成员变量的初始化&#xff0c;内置类型的初始化是在生成的同时赋值而且仅有一次&#xff0c;但是在构造函数体内是能对成员变量进行多次赋值的。所以在函数体内的…

探索OpenCV:图像处理基础与实践

探索OpenCV&#xff1a;图像处理基础与实践 前言图像读取基础安装OpenCV库读取彩色与灰度图像 RGB颜色模型颜色通道解析单通道图像显示 感兴趣区域&#xff08;ROI&#xff09;图像处理进阶技巧图像打码图像组合图像缩放 结语 前言 在当今数字化时代&#xff0c;图像不仅是我们…

详谈进程等待

目录 前言1. 进程等待的必要性1.1 进程等待的定义 2. 如何进行进程等待2.1 wait 单进程2.2 wait 多进程2.3 status && 退出情况2.3.1 status 参数构成2.3.2 简证 status 参数构成2.3.3 进程等待失败2.3.4 宏调用查看退出信息 3. 进程等待的原理 前言 本篇文章继上一篇…

Hive SQL

一、基本数据类型 tinyint 1byte 有符号整数 smallint 2byte 有符号整数 int 4byte 有符号整数 bigint 8byte 有符号整数 boolean 布尔类型&#xff0c;true或者false float 单精度浮点数 double 双精度浮点数 decim…

C语言07---指针进阶

指针万能拆解法 char型指针 char型指针实质上跟别的类型的指针并无本质区别&#xff0c;但由于C语言中的字符串以字符数组的方式存储&#xff0c;而数组在大多数场合又会表现为指针&#xff0c;因此字符串在绝大多数场合就表现为char型指针。 定义&#xff1a; char *p &qu…

区块链国赛第六套样题(关于运维)

任务1-2&#xff1a;区块链系统部署与运维 围绕食品安全溯源区块链平台部署与运维需求&#xff0c;进行项目相关系统、节点以及管理工具的部署工作。通过监控工具完成对网络、节点服务的监控。最终利用业务需求规范&#xff0c;完成系统日志、网络参数、节点服务等系统结构的维…

Hadoop的HA配置与实现(ZooKeeper)

目录 一、Hadoop的HA架构二、配置实现Hadoop的HA三、效果 一、Hadoop的HA架构 集群规划 112&#xff1a;NameNode1 ResourceManager1 JournalNode1 113&#xff1a;NameNode2 ResourceManager2 JournalNode2 114&#xff1a;DataNode1 NodeManager1 115&#xff1a;DataNode2 N…

linux 云主机下载 rpm 包安装 oracle java jdk21 实录(华为云 EulerOS)

本来是想通过 yum install 相关的 openjdk 版本的, 但老是提示说找不到, 也不想去配置相关的仓库了, 所以改成去 oracle 官网下载 jdk21 的 rpm 包来安装. 云主机是华为云的 EulerOS , 具体为 Huawei Cloud EulerOS 2.0 标准版 64位(公共镜像), 相对于用的比较熟 centos, 差别…

学习之在window上安装MySQL server 并连接到Navicat

一、下载 下载地址&#xff1a;https://www.mysql.com/ 二、安装 1、双击软件安装2、点击yes

云计算实训36——mysql镜像管理、同步容器和宿主机时间、在容器外执行容器内命令、容器的ip地址不稳定问题、基础镜像的制作、镜像应用

一、线上考试系统的数据虚拟化技术部署 1.部署前段服务器 步骤一&#xff1a;将资源上传到服务器 将dist.zip上传给服务器 下载unzip的包 yum -y install unzip 解压 unzip dist.zip 步骤二&#xff1a;创建基础容器在服务器上 启动服务 systemctl start docker.servic…

用 Go 语言实现常见的十大排序算法(上)

十大常见的排序算法有&#xff1a; 冒泡排序&#xff08;Bubble Sort&#xff09; 选择排序&#xff08;Selection Sort&#xff09; 插入排序&#xff08;Insertion Sort&#xff09; 希尔排序&#xff08;Shell Sort&#xff09; 归并排序&#xff08;Merge Sort&#xf…

<数据集>考场行为识别数据集<目标检测>

数据集格式&#xff1a;VOCYOLO格式 图片数量&#xff1a;2192张 标注数量(xml文件个数)&#xff1a;2192 标注数量(txt文件个数)&#xff1a;2192 标注类别数&#xff1a;2 标注类别名称&#xff1a;[cheating, good] 序号类别名称图片数框数1cheating128214412good1067…

气膜建筑与装配式建筑的对比分析—轻空间

在现代建筑中&#xff0c;气膜建筑和装配式建筑都作为新型建筑形式受到关注。然而&#xff0c;在很多应用场景中&#xff0c;气膜建筑展现出了比装配式建筑更为明显的优势。以下将着重对比气膜建筑相较于装配式建筑的独特优势。 气膜建筑的突出优势 1. 更快的施工速度 气膜建筑…

在 Debian 上安装 IntelliJ IDEA 笔记

在 Debian&#x1f4a9; 上安装 IntelliJ IDEA &#x1f4a1; 笔记 下载安装 JDK17安装 IntelliJ IDEA Community添加桌面启动项&#xff08;快捷方式&#xff09; 参考资料 下载 两个包已经下好了&#xff0c;一个JDK17&#xff0c;一个IntelliJ IDEA Community 使用 wget ur…

微信对话开放平台接口源码分享

文章目录 📖 介绍 📖🏡 演示环境 🏡📒 接口源码 📒⚓️ 相关链接 ⚓️📖 介绍 📖 微信对话开放平台是微信官方授权的智能对话技术平台,旨在帮助开发者及非开发者快速搭建智能对话机器人(智能客服),并轻松接入微信公众号、小程序、企业微信等微信生态中的各…