参考
https://blog.csdn.net/qq_43114229/article/details/124078914
https://kubernetes.io/zh-cn/docs/tasks/run-application/run-replicated-stateful-application/
MySQL主从同步架构图
mysql-0是master
mysql-1和mysql-2是两个备份
当mysql写的时候,找headless service中的mysql-0.mysql;当mysql读的时候,找clusterip service中的mysql读,实现读写分离。
statefulset维护三个副本,一个主两个从
因为主从的配置不同所以通过configmap来解决主从配置不同的问题
- 配置configmap
# cat 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 # 主mysql激活二进制日志
slave.cnf: |
# Apply this config only on slaves.
[mysqld]
super-read-only # 从mysql上面设置为只读
生成配置
# kubectl apply -f configmap.yaml
查看
# kubectl get cm mysql
NAME DATA AGE
mysql 2 9s
- 创建service服务
# cat service.yaml
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
创建service
# kubectl apply -f service.yaml
service/mysql created
service/mysql-read created
查看service
# kubectl get svc mysql mysql-read
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
mysql ClusterIP None <none> 3306/TCP 42s
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
mysql-read ClusterIP 10.0.0.214 <none> 3306/TCP 42s
- statefulset配置
# cat statefulset.yaml
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql
spec:
selector:
matchLabels:
app: mysql
serviceName: mysql
replicas: 2
template:
metadata:
labels:
app: mysql
spec:
initContainers:
- name: init-mysql
image: mysql:5.7
#image: mysql:8.0.36
command:
- bash
- "-c"
- |
set -ex
# Generate mysql server-id from pod ordinal index.
[[ `hostname` =~ -([0-9]+)$ ]] || exit 1
#[[ `hostid` =~ -([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: xtrabackup:1.0
image: 192.168.3.61/foundation/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
#[[ `hostid` =~ -([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: 500Mi
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: xtrabackup:1.0
image: 192.168.3.61/foundation/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 && "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_info
elif [[ -f xtrabackup_binlog_info ]]; then
# We're cloning directly from master. Parse binlog position.
[[ `cat xtrabackup_binlog_info` =~ ^(.*?)[[:space:]]+(.*?)$ ]] || exit 1
rm -f xtrabackup_binlog_info xtrabackup_slave_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"
mysql -h 127.0.0.1 \
-e "$(<change_master_to.sql.in), \
MASTER_HOST='mysql-0.mysql', \
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.orig
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
volumes:
- name: conf
emptyDir: {}
- name: config-map
configMap:
name: mysql
volumeClaimTemplates:
- metadata:
name: data
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: gluster-heketi-storageclass
resources:
requests:
storage: 10Gi
注意配置storageClassName动态存储
创建statefulset和pvc
# kubectl apply -f statefulset.yaml
查看创建的pvc
设置了几个副本则有几个pvc
# kubectl get pvc data-mysql-0 data-mysql-1
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
data-mysql-0 Bound pvc-980d613d-dac3-11ee-b17f-525400e71cb5 10Gi RWO gluster-heketi-storageclass 42m
NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE
data-mysql-1 Bound pvc-ae563992-dac3-11ee-b17f-525400e71cb5 10Gi RWO gluster-heketi-storageclass 42m
查看初始化日志输出
# kubectl logs mysql-0 -c init-mysql
++ hostname
+ [[ mysql-0 =~ -([0-9]+)$ ]]
+ ordinal=0
+ echo '[mysqld]'
+ echo server-id=100
+ [[ 0 -eq 0 ]]
+ cp /mnt/config-map/master.cnf /mnt/conf.d/
查看pod的配置文件
# kubectl exec mysql-0 -c mysql -- ls /etc/mysql/conf.d
master.cnf
server-id.cnf
# kubectl exec mysql-1 -c mysql -- ls /etc/mysql/conf.d
server-id.cnf
slave.cnf
查看配置文件内容
# kubectl exec mysql-0 -c mysql -- cat /etc/mysql/conf.d/master.cnf
# Apply this config only on the master.
[mysqld]
log-bin # 主mysql激活二进制日志
# kubectl exec mysql-1 -c mysql -- cat /etc/mysql/conf.d/slave.cnf
# Apply this config only on slaves.
[mysqld]
super-read-only # 从mysql上面设置为只读
查看生成的Pod
# kubectl get pod mysql-0 mysql-1
NAME READY STATUS RESTARTS AGE
mysql-0 2/2 Running 0 5m32s
NAME READY STATUS RESTARTS AGE
mysql-1 2/2 Running 0 5m22s
- 创建NodePort端口
K8S集群内可以使用DNS使用域名mysql-0.mysql访问
在集群外部访问创建NodePort
# cat mysql-service.yaml
apiVersion: v1
kind: Service
metadata:
creationTimestamp: null
labels:
app: mysql
controller-revision-hash: mysql-79b5fcf7cc
statefulset.kubernetes.io/pod-name: mysql-0
name: mysql-0
spec:
ports:
- port: 3306
protocol: TCP
targetPort: 3306
nodePort: 33306
selector:
app: mysql
controller-revision-hash: mysql-79b5fcf7cc
statefulset.kubernetes.io/pod-name: mysql-0
type: NodePort
status:
loadBalancer: {}
创建svc
# kubectl apply -f mysql-service.yaml
查看svc
# kubectl get svc mysql-0
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
mysql-0 NodePort 10.0.0.118 <none> 3306:33306/TCP 44s
访问并修改root密码
默认root无密码 通过node节点ip和NodePort端口访问
# mysql -uroot -p -h192.168.3.65 -P 33306
删除用户并新建用户设置密码并授权
MySQL [(none)]> drop user root@'%';
Query OK, 0 rows affected (0.02 sec)
MySQL [(none)]> create user root@'%' identified by 'password';
Query OK, 0 rows affected (0.01 sec)
MySQL> grant all on *.* to 'root'@'%';
Query OK, 0 rows affected (0.01 sec)
MySQL [(none)]> flush privileges;
Query OK, 0 rows affected (0.01 sec)
登录从节点查看主从同步状态
# kubectl exec -it mysql-1 bash
mysql> show slave status\G
*************************** 1. row ***************************
Slave_IO_State: Waiting for master to send event
Master_Host: mysql-0.mysql
Master_User: root
Master_Port: 3306
Connect_Retry: 10
Master_Log_File: mysql-0-bin.000005
Read_Master_Log_Pos: 2062
Relay_Log_File: mysql-1-relay-bin.000005
Relay_Log_Pos: 2279
Relay_Master_Log_File: mysql-0-bin.000005
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
以下两个状态为Yes则代表主从状态正常
Slave_IO_Running: Yes
Slave_SQL_Running: Yes
4. 清理
# kubectl delete -f configmap.yaml
# kubectl delete -f service.yaml
# kubectl delete -f mysql-service.yaml
# kubectl delete -f statefulset.yaml
不会清理pvc手动删除pvc
# kubectl delete pvc data-mysql-0
persistentvolumeclaim "data-mysql-0" deleted
# kubectl delete pvc data-mysql-1
persistentvolumeclaim "data-mysql-1" deleted
标签:kubectl,name,MySQL5.7,xtrabackup,master,conf,mysql,K8S,主从 From: https://www.cnblogs.com/minseo/p/18054392把statefulset的副本数修改为3则为一主两从的架构