因为MySQL是一个有状态的应用,使用Deployment的方式部署不是很方便
参考了官方文档,修改为MySQL8版本。
创建ConfigMap
apiVersion: v1
kind: ConfigMap
metadata:
name: mysql
labels:
app: mysql
data:
master.cnf: |
# Apply this config only on the master.
[client]
default-character-set=utf8mb4
[mysql]
default-character-set=utf8mb4
[mysqld]
# 打开binlog日志
log-bin
binlog_expire_logs_seconds=2592000
max_connections=10000
# 在容器里面需要设置下时区
default-time-zone='+8:00'
character-set-client-handshake=FALSE
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
init_connect='SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci'
slave.cnf: |
# Apply this config only on slaves.
[client]
default-character-set=utf8mb4
[mysql]
default-character-set=utf8mb4
[mysqld]
# 机器设置只读
super-read-only
max_connections=10000
default-time-zone='+8:00'
character-set-client-handshake=FALSE
character-set-server=utf8mb4
collation-server=utf8mb4_unicode_ci
init_connect='SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci'
$ kubectl create -f configmap.yml
这个ConfigMap分别提供了my.cnf的覆盖,可以独立控制 MySQL 主服务器和从服务器的配置。
创建Service
apiVersion: v1
kind: Service
metadata:
name: mysql-svc-master
labels:
app: mysql
spec:
selector:
app: mysql
ports:
- port: 3306
name: mysql
clusterIP: None
$ kubectl create -f service.yml
需要先创建一个Headless Service,用于从机去访问主机。从机可以通过<pod-name>.mysql-svc-master去访问到指定的pod。
创建StorageClass
这一步可以不需要。如果有创建好的StorageClass可以直接使用,这里主要是给StatefulSet创建PV使用。
StatefulSet
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mysql-ss
spec:
selector:
matchLabels:
app: mysql # 匹配 .spec.template.metadata.labels
serviceName: mysql-svc-master
replicas: 3
template:
metadata:
labels:
app: mysql # 匹配 .spec.selector.matchLabels
spec:
initContainers:
- name: init-mysql
image: mysql:8.0
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: mzmuer/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-ss-$(($ordinal-1)).mysql-svc-master 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:8.0
args: ["--default-authentication-plugin=mysql_native_password"]
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: 250m
memory: 256Mi
limits:
cpu: 500m
memory: 512Mi
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: mzmuer/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 [[ -s 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 -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 <<EOF
$(<change_master_to.sql.orig),
MASTER_HOST='mysql-ss-0.mysql-svc-master',
MASTER_USER='root',
MASTER_PASSWORD='',
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"
volumeMounts:
- name: data
mountPath: /var/lib/mysql
subPath: mysql
- name: conf
mountPath: /etc/mysql/conf.d
resources:
requests:
cpu: 100m
memory: 100Mi
limits:
cpu: 200m
memory: 200Mi
volumes:
- name: conf
emptyDir: {}
- name: config-map
configMap:
name: mysql
volumeClaimTemplates:
- metadata:
name: data
spec:
# 这里需要注意下,要修改为自己的StorageClass的名称
storageClassName: mysql-sc
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
$ kubectl create -f statefulclass.yml
这个编排文分为一下几块:
- init-mysql
初始化配置文件和server-id文件,分别给主机和从机不同的配置文件。 - clone-mysql
初始化mysql。如果是从机需要先用xtrabackup做一次全量的备份,备份的数据来自于前一个pod。 - mysql
按照配置启动mysql - xtrabackup
执行命令启动slave,并利用ncat启动监听,如果扩展新的节点,传输数据到新节点。
最后
kubectl get pods -l app=mysql
NAME READY STATUS RESTARTS AGE
mysql-ss-0 2/2 Running 0 5h6m
mysql-ss-1 2/2 Running 0 5h6m
mysql-ss-2 2/2 Running 1 5h5m
官方文档是MySQL5.7。修改为MySQL8主要需要解决的是xtrabackup的版本问题 ,这里自己做一个xtrabackup8的镜像。
所有编排文件都在 https://github.com/mzmuer/k8s-yml/tree/master/mysql