Kubernetes – Simple CronJob for MySQL/MariaDB Backup


No Secret, No Configmap, No Fuzz.

Just a command and args one-liner that gets the job done, day after day, with an invaluable result on the day that you reaaaally need it.

Example Backup Cron:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: backup-database
  namespace: <NAMESPACE>
spec:
  concurrencyPolicy: Forbid
  schedule: "@daily"
  successfulJobsHistoryLimit: 2
  failedJobsHistoryLimit: 2
  jobTemplate:
    spec:
      backoffLimit: 2
      template:
        spec:
          nodeSelector:
            kubernetes.io/hostname: K8S-WORKER-01
          restartPolicy: Never
          containers:
            - name: backup-mariadb
              image: bigtruedata/mysqldump
              command: ["/bin/sh"]
              args: ["-c", "mysqldump -h HOSTNAME_TO_MYSQL_SVC -uMYSQL_USER -pMYSQL_PASSWORD MYSQL_DB | gzip -9 > /data/MYSQL_DB-$(date +%A).sql.gz"]
              volumeMounts:
                  - mountPath: /data
                    name: database-mysqldump
          volumes:
            - name: database-mysqldump
              hostPath:
                path: /home/$USER/backups/database


This will create a daily job (00:00, 12AM) that runs container image “mysqldump”, generously authored by docker.io/bigtruedata. It will store the dump in compressed Gzip format on specified worker node and specified hostPath.

kubernetes.io/hostname – Worker node to run container and store dump.
hostPath:
path: /backup/path – Path on worker node to store dump
HOSTNAME_TO_MYSQL_SVC
– Target database pod
MYSQL_USER – MySQL/MariaDB User
MYSQL_PASSWORD – MySQL/MariaDB User Password
MYSQL_DB – Database to dump
/data/MYSQL_DB-$(date +%A).sql.gz – MySQL Dump with weekday in name

Restore procedure:

Unzip dump:

gunzip /home/$USER/backups/database/MYSQL_DB-Thursday.sql.gz

Restore database from dump:

kubectl exec -i MYSQLPOD -- mysql -uMYSQL_USER -pMYSQL_PASSWORD MYSQL_DB < /home/$USER/backups/database

Happy dumping! 💽



Leave a Reply

Your email address will not be published.