aOko8g.jpg

由于近期有项目上线,mysql部署在k8s中。此文档用来记录使用cronjob来实现定时备份mysql数据库的过程。

环境:centos7.6、Kubernetes1.14.3、 持久化存储为CephFS、mysql5.7.21

创建StorageClass

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
$ vim StorageClass.yaml
kind: StorageClass
apiVersion: storage.k8s.io/v1
metadata:
  name: mysql-backup-prod
provisioner: ceph.com/cephfs
parameters:
    monitors: 172.16.77.53:6789
    adminId: admin
    adminSecretName: ceph-secret-admin-53 #此处名称要和集群中的ceph密码对应
    adminSecretNamespace: "storage"
    claimRoot: /volumes/kubernetes/masks-prod/mysql-backup
$ kubectl apply -f StorageClass.yaml

创建pvc

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
$ vim pvc.yaml
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: mysql-backup
  annotations:
    volume.beta.kubernetes.io/storage-class: "mysql-backup-prod"
spec:
  accessModes: [ "ReadWriteMany" ]
  resources:
    requests:
      storage: 2Gi
      
$ kubectl apply -f pvc.yaml

创建cronjob

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
$ vim mysql-CronJob.yaml
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: mysql-backup
spec:
  schedule: "0 0 * * * "
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: mysql-backup
            imagePullPolicy: IfNotPresent
            image: mysql:5.7.21
            env:
            - name: MYSQL_BACKUP_USER
              value: root
            - name: MYSQL_BACKUP_USER_PASSWORD
              value: passwd
            - name: MYSQL_HOST
              value: mysql
            command:
            - /bin/sh
            - -c
            - |
              set -ex
              mysqldump --host=172.16.xx.xx -P 3307 --user=root \
                        --password=123456 \
                        --databases masks_s   \
                        > /mysql-backup/mysql-`date +'%Y%m%d_%H_%M_%S'`.sql \
                        & /usr/bin/find  /mysql-backup/* -mtime +10 -exec rm {} \; #删除修改时间为10天之前的文件
            volumeMounts:
            - name: mysql-backup
              mountPath: /mysql-backup
          restartPolicy: OnFailure
          volumes:
          - name: mysql-backup
            persistentVolumeClaim:
              claimName: mysql-backup
$ kubectl apply -f mysql-CronJob.yaml

此cronjob会在每天0点备份masks_s数据库,并清除10天之前的备份文件