在 k8s 中使用 cronjob 备份 mongodb
---
apiVersion: batch/v1beta1
kind: CronJob
metadata:
annotations: {}
labels:
k8s.kuboard.cn/name: mongodb-backup
name: mongodb-backup
namespace: ac-data
spec:
concurrencyPolicy: Replace
failedJobsHistoryLimit: 1
jobTemplate:
metadata:
creationTimestamp: null
labels:
k8s.kuboard.cn/name: mongodb-backup
spec:
template:
metadata:
creationTimestamp: null
spec:
containers:
- command:
- /app/backup.sh
env:
- name: URI
value: >-
mongodb://user:pwd@mongodb-name-headless.ac-data.svc:27017/db?replicaSet=rs0
image: 'mongodb:7.0.2-debian-11-r7'
imagePullPolicy: IfNotPresent
name: c0
resources: {}
securityContext:
runAsGroup: 0
runAsUser: 0
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
volumeMounts:
- mountPath: /data
name: volume-data
subPath: db-backup
- mountPath: /app
name: volume-scripts
dnsPolicy: ClusterFirst
restartPolicy: Never
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 30
volumes:
- name: volume-data
nfs:
path: /mnt
server: 10.11.123.111
- configMap:
defaultMode: 511
name: mongo-backup
name: volume-scripts
schedule: 5 0 * * *
successfulJobsHistoryLimit: 3
suspend: false
---
apiVersion: v1
data:
backup.sh: |-
#!/bin/bash
ROOT_PATH=/data
BACKUP_PREFIX=mongodb_backup_
DATE=`TZ=Asia/Shanghai date +%Y-%m-%d_%H%M`
BACKUP_DIR=${ROOT_PATH}/${BACKUP_PREFIX}${DATE}
echo "back up mongodb to ${BACKUP_DIR}"
# run command to back
mongodump --uri="${URI}" --out=${BACKUP_DIR}
# delete old backup
cutoff=$(date -d '7 days ago' +%s)
for folder in ${ROOT_PATH}/*; do
# if directory name startwith backup_ and create before 7 days ago will be deleted
if [[ -d "$folder" ]] && [[ $(basename "$folder") == "$BACKUP_PREFIX"* ]]; then
timestamp=$(echo "$folder" | grep -oP '\d{4}-\d{2}-\d{2}' | date -f - '+%s')
if (( timestamp < cutoff )); then
echo "directory ${folder} will be deleted"
rm -rf "$folder"
fi
fi
done
echo "Done"
kind: ConfigMap
metadata:
annotations: {}
labels: {}
name: mongo-backup
namespace: ac-data