目录
主可以读写,从只读。
分析需要解决的问题,制定解决思路:
1.启动顺序:Master 的Pod 必须先于 Slave 的 Pod 起来;
2.如果某个Pod挂掉了,应该自动重新启动一个Pod,这个新建的Pod应该沿用原来的数据;
3.Master 与 Slave 的配置文件不同,特别是server_id;
4.Master 与 Slave 在服务启动之后还需要执行一些命令,它们也不一样,具体为:
1)Master需要执行授权命令,授权的用户名和密码希望用户自己来配置,而不是写死;
2)Slave需要执行CHANGE MASTER命令,需要知道Master的地址。
1.关于启动顺序问题。这个好说,利用 StatefulSet 轻松就能解决,它的一个特点就是会将所有的Pod副本进行编号,然后按照编号顺序一个一个的启动,Pod命名规则为 statefulsetName-N 其中N为编号,从0开始。例如,StatefulSet名称为 mysql ,那么第一个启动的Pod名称必为 mysql-0 。
2.关于重建Pod后的数据问题。因为重建的新Pod不一定还在原来的Node上,因此,想用原来的数据必须要使用分布式或共享Volume。我们可以使用NFS或其它的分布式存储来解决此问题。另外,如果几个副本(例如mysql-1,mysql-2,mysql-3)同时重建,必须保证新建立的 mysql-1 仍然沿用原来的 mysql-1 的数据。这个问题我们可以使用PV和PVC来解决。
3.配置文件不同的问题。不考虑其他,就server_id不同的问题,我们可以利用容器启动前的initContainer来解决在每个容器启动前插入更改配置文件信息,还可以传入容器启动后执行的脚本文件。
4.用户名和密码可以使用 Secret 传递进来(我这里使用的configmap,二者同类,都是挂载进去)Master地址因为不是固定的,所以不建议使用IP地址,我们可以借助 Headless Service 加上 DNS 来解决。如果我们能传入Service的名称进来,那么就可以使用这种方式来与其它Pod进行通信:PodName.ServiceName 。例如,如果Service名称为mysqlsvc,那么master的DNS名称为 mysql-0.mysqlsvc ,这个名称是不会变化的。当Master完成授权工作后,Slave可通过授权帐号查询到binlog文件名及位置信息(注意授权时要给 replication client 权限才可以查询)。
最后,我们直接上。
一、设置密码版本:
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
---
apiVersion: v1
kind: ConfigMap
metadata:
name: mconfig
labels:
app: mconfig
data:
passwd.cnf: |
[mysql]
user=root
password=123456
[mysqladmin]
user=root
password=123456
---
# application/mysql/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
---
#application/mysql/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.37
# 为每个MySQL节点配置service-id
# 如果节点序号是0,则使用master的配置, 其余节点使用slave的配置
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: registry.cn-shenzhen.aliyuncs.com/lishanbin/xtrabackup:2.4
# 为除了节点序号为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 --user=root --password='123456' --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.37
env:
- name: MYSQL_ROOT_PASSWORD
value: "123456"
ports:
- name: mysql
containerPort: 3306
volumeMounts:
- name: data
mountPath: /var/lib/mysql
subPath: mysql
- name: conf
mountPath: /etc/mysql/conf.d
- name: mconfig
mountPath: /var/passwd.cnf
subPath: passwd.cnf
resources:
requests:
cpu: 100m
# Mi是兆的意思,需要100M 内存
memory: 100Mi
livenessProbe:
# 使用mysqladmin ping命令,对MySQL节点进行探活检测
# 在节点部署完30秒后开始,每10秒检测一次,超时时间为5秒
exec:
command: [ "mysqladmin","--defaults-extra-file=/var/passwd.cnf", "ping" ]
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
readinessProbe:
# 对节点服务可用性进行检测, 启动5秒后开始,每2秒检测一次,超时时间1秒
exec:
# Check we can execute queries over TCP (skip-networking is off).
command: [ "mysql", "--defaults-extra-file=/var/passwd.cnf", "-h", "127.0.0.1", "-e", "SELECT 1" ]
initialDelaySeconds: 5
periodSeconds: 2
timeoutSeconds: 1
- name: xtrabackup
image: registry.cn-shenzhen.aliyuncs.com/lishanbin/xtrabackup:2.4
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 -p'123456' -e "SELECT 1"; do sleep 1; done
echo "Initializing replication from clone position"
mysql -h 127.0.0.1 -p'123456' \
-e "$(<change_master_to.sql.in), \
MASTER_HOST='mysql-0.mysql', \
MASTER_USER='root', \
MASTER_PASSWORD='123456', \
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 --password='123456' --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
- name: mconfig
configMap:
name: mconfig
items:
- key: passwd.cnf
path: passwd.cnf
# 设置PVC
volumeClaimTemplates:
- metadata:
name: data
annotations:
volume.beta.kubernetes.io/storage-class: local-path
spec:
storageClassName: local-path
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
二、免密版本
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
---
# application/mysql/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
---
#application/mysql/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.37
# 为每个MySQL节点配置service-id
# 如果节点序号是0,则使用master的配置, 其余节点使用slave的配置
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: registry.cn-shenzhen.aliyuncs.com/lishanbin/xtrabackup:2.4
# 为除了节点序号为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.37
# 设置支持免密登录
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:
# 设置启动pod需要的资源,官方文档上需要500m cpu,1Gi memory。
# 我本地测试的时候,会因为资源不足,报1 Insufficient cpu, 1 Insufficient memory错误,所以我改小了点
requests:
# m是千分之一的意思,100m表示需要0.1个cpu
cpu: 100m
# Mi是兆的意思,需要100M 内存
memory: 100Mi
livenessProbe:
# 使用mysqladmin ping命令,对MySQL节点进行探活检测
# 在节点部署完30秒后开始,每10秒检测一次,超时时间为5秒
exec:
command: [ "mysqladmin", "ping" ]
initialDelaySeconds: 30
periodSeconds: 10
timeoutSeconds: 5
readinessProbe:
# 对节点服务可用性进行检测, 启动5秒后开始,每2秒检测一次,超时时间1秒
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: registry.cn-shenzhen.aliyuncs.com/lishanbin/xtrabackup:2.4
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
# 设置PVC
volumeClaimTemplates:
- metadata:
name: data
annotations:
volume.beta.kubernetes.io/storage-class: local-path
spec:
storageClassName: local-path
accessModes: [ "ReadWriteOnce" ]
resources:
requests:
storage: 1Gi
三、验证:
kubectl -n mysql exec mysql-1 -c mysql -- bash -c "mysql -uroot -p123456 -e 'show slave status \G'"