一、configmap
数据库备份脚本写入k8s环境的configmap文件,并生成config。
# cat mysql-back-configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: mysql8back
namespace: crontabs
data:
mysql8back.sh: |
#!/bin/bash
DUMPDIR=/tmp
#backup
backupDate=`date +%Y%m%d`
DB_LIST=/tmp/mydb.lst
mysql -h mysql8-primary.mysql8.svc.cluster.local -u root -pXXXXXX -N -e"show databases" > $DB_LIST 2>/dev/null
if [ -s ]
then
cat $DB_LIST |while read LINE
do
mysqldump -h mysql8-primary.mysql8.svc.cluster.local -u root -pXXXXXX --opt --single-transaction --set-gtid-purged=OFF $LINE > ${DUMPDIR}/$LINE-$backupDate.sql
tar -czf ${DUMPDIR}/$LINE-$backupDate.tar.gz ${DUMPDIR}/$LINE-$backupDate.sql
rm -rf ${DUMPDIR}/$LINE-$backupDate.sql
done
else
echo "No databases list get !"
fi
#remove tar
removeTarDate=`date -d "5 days ago" +%Y%m%d`
rm -rf ${DUMPDIR}/*-$removeTarDate.tar.gz
# kubectl create ns crontabs
# kubectl apply -f mysql-back-configmap.yaml
二、镜像部署
存储类得自己提前创建
# cat backup.yaml
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mysql8bak
namespace: crontabs
spec:
storageClassName: "nfs-hdd"
accessModes:
- ReadWriteMany
resources:
requests:
storage: 20Gi
---
apiVersion: batch/v1
kind: CronJob
metadata:
name: mysql8backup
namespace: crontabs
spec:
schedule: "0 0 * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: mysql8backup
image: dhub.kubesre.xyz/databack/mysql-backup:latest
command: ["/bin/bash", "/opt/mysql8back.sh"]
#args:
# - /opt/mysql8back.sh
lifecycle:
postStart:
exec:
command: ["bash", "chmod +x /opt/mysql8back.sh"]
preStop:
exec:
command: ["bash", "/opt/mysql8back.sh"]
volumeMounts:
- name: logs
mountPath: /tmp
- name: mysql8backup
mountPath: /opt
volumes:
- name: logs
persistentVolumeClaim:
claimName: mysql8bak
- name: mysql8backup
configMap:
name: mysql8back
items:
- key: "mysql8back.sh"
path: "mysql8back.sh"
restartPolicy: OnFailure
# kubectl apply -f backup.yaml
三、简单使用
# kubectl get cronjob -n crontabs -o wide
# kubectl get pod -n crontabs -o wide
# kubectl describe cronjob mysql8backup -n crontabs
# kubectl logs pod/mysql8backup-28719610-knzd8 -n crontabs