How to Back Up MySQL Databases in Kubernetes: 3 Proven Methods

Backing up MySQL in Kubernetes is vital due to the platform’s dynamic nature. This article shows three clear ways to secure your data so you can recover fast after any failure.

download-icon
Free Download
for VM, OS, DB, File, NAS, etc.
dan-zeng

Updated by Dan Zeng on 2025/11/21

Table of contents
  • What Is Kubernetes MySQL Backup

  • Why Backup MySQL in Kubernetes?

  • Method 1: Backing Up MySQL in Kubernetes Using mysqldump

  • Method 2 – Backing Up MySQL in Kubernetes Using Percona XtraBackup

  • Method 3 – Backing Up MySQL in Kubernetes Using Percona Operator

  • How to Back Up MySQL Workloads in Kubernetes with Vinchin Backup & Recovery

  • FAQs about Kubernetes MySQL Backup

  • Conclusion

Backing up MySQL database in Kubernetes is critical for any business that values its data. Kubernetes offers flexibility and scalability but adds complexity to database management tasks like backup and recovery. Without a strong kubernetes mysql backup plan, you risk losing vital information due to accidents or failures. In this guide, we’ll explore how to protect your MySQL data in Kubernetes using several proven methods—from basic tools to advanced automation—so you can keep your business running smoothly no matter what happens.

What Is Kubernetes MySQL Backup

Kubernetes MySQL backup means creating safe copies of your MySQL databases running inside Kubernetes clusters. Unlike traditional setups where databases run on fixed servers, Kubernetes uses containers that can move between nodes or restart at any time. This dynamic environment requires special strategies for reliable backups.

A proper kubernetes mysql backup captures both your database data and the related Kubernetes resources—like Deployments or StatefulSets—that define how your application runs. By backing up both parts, you ensure you can recover not just the raw data but also restore your application’s full environment if disaster strikes.

Why Backup MySQL in Kubernetes?

Why is kubernetes mysql backup so important? Data loss can happen at any time due to hardware failure, human error, software bugs—or even malicious attacks. In Kubernetes environments, pods are ephemeral by design; they may disappear when nodes fail or during upgrades unless persistent storage is used correctly.

Regular backups help you recover from these events quickly with minimal downtime or data loss. They also support migrations between clusters or cloud providers and help meet compliance requirements for regulated industries. Backups make it easier to test changes safely or roll back after failed updates—a must-have for agile teams working at scale.

Method 1: Backing Up MySQL in Kubernetes Using mysqldump

The simplest way to perform a kubernetes mysql backup is with mysqldump. This tool exports all database contents into a single SQL file that you can store anywhere—even outside your cluster if needed.

Before starting, remember that mysqldump works best for small-to-medium databases because it locks tables during export unless you use options like --single-transaction (recommended for InnoDB tables). For larger workloads or high-write activity periods, consider other methods described later in this guide.

To automate regular backups using mysqldump, follow these steps:

First, create a Secret containing your MySQL credentials within the same namespace as your database:

apiVersion: v1
kind: Secret
metadata:
  name: mysql-secret
  namespace: my-database-namespace
type: Opaque
data:
  username: <base64-encoded-username>
  password: <base64-encoded-password>

Next, set up a PersistentVolumeClaim (PVC) where backups will be stored:

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql-backup-pvc
  namespace: my-database-namespace
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi

Now define a CronJob that runs nightly at 2 AM:

apiVersion: batch/v1
kind: CronJob
metadata:
  name: mysql-backup-job
  namespace: my-database-namespace
spec:
  schedule: "0 2 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: mysql-backup-container
            image: mysql:8.0 # Includes mysqldump by default.
            command: ["/bin/sh", "-c"]
            args:
              - |
                mysqldump --single-transaction -u$MYSQL_USER -p$MYSQL_PASSWORD -h $MYSQL_HOST --all-databases > /backup/backup-$(date +\%F).sql;
            env:
            - name: MYSQL_USER
              valueFrom:
                secretKeyRef:
                  name: mysql-secret
                  key: username
            - name: MYSQL_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: mysql-secret
                  key: password
            - name: MYSQL_HOST 
              value: "mysql-service"
            volumeMounts:
            - name: backup-storage 
              mountPath: /backup 
          restartPolicy: OnFailure 
          volumes:
          - name: backup-storage 
            persistentVolumeClaim:
              claimName: mysql-backup-pvc

This job writes daily SQL dumps into /backup inside the PVC so they persist even if pods are deleted or rescheduled elsewhere in the cluster.

To further protect against node failures or disasters affecting an entire cluster zone, copy these files offsite using tools like kubectl cp, SFTP clients installed inside another pod container (alpine + openssh-client), or cloud CLI utilities such as AWS CLI (aws s3 cp). Always verify backups regularly by restoring them into a test environment!

If you need point-in-time recovery capabilities beyond daily snapshots—for example during heavy write loads—consider enabling binary logging on MySQL (log_bin) so incremental changes are captured too.

Method 2 – Backing Up MySQL in Kubernetes Using Percona XtraBackup

For larger databases or when hot consistent backups are required without long table locks, Percona XtraBackup is often preferred over logical dump tools like mysqldump. XtraBackup creates physical copies of data files while allowing ongoing writes—a big advantage for production systems handling many transactions per second.

Step-by-Step XtraBackup Setup in Kubernetes

First things first—you need both your main MySQL container and an additional sidecar container running XtraBackup within the same pod so they share access to /var/lib/mysql. Here’s how it works:

1. Define a shared PVC mounted at /var/lib/mysql (for both containers) plus another PVC mounted at /backup (for storing output).

2. Use an official Percona image with XtraBackup installed (percona/percona-xtrabackup) as your sidecar.

3. Run this command inside the sidecar container:

   xtrabackup --backup --target-dir=/backup --host=127.0.0.1 --user=<user> --password=<password>

4. After completion prepare the backup files using:

   xtrabackup --prepare --target-dir=/backup

5. To restore later simply stop MySQL server then copy prepared files back into /var/lib/mysql.

Here’s an example Pod definition snippet showing two containers sharing volumes:

apiVersion: v1 
kind : Pod 
metadata :
    name : mysql-with-xtrabackup 
    namespace : my-database-namespace  
spec :
    containers :
      - name : mysql-server  
        image : percona/percona-server  
        volumeMounts :
           - mountPath : /var/lib/mysql  
             name : datadir  
      - name : xtrabackup-sidecar  
        image : percona/percona-xtrabackup  
        command : ["sleep", "infinity"] # Replace with actual script/command as needed.
        volumeMounts :
           - mountPath : /var/lib/mysql  
             name : datadir  
           - mountPath : /backup  
             name : backupdir   
    volumes :
       - name : datadir   
         persistentVolumeClaim :
           claimName : my-mysql-data-pvc   
       - name : backupdir   
         persistentVolumeClaim :
           claimName : xtrabackup-output-pvc

You may automate this process via CronJobs launching temporary pods configured similarly above; after each run upload results offsite using S3 CLI tools if desired.

Troubleshooting Tips

If permissions errors occur during file copying/restoration steps check user IDs between containers match those used by mysqld/XtraBackup processes.

Method 3 – Backing Up MySQL in Kubernetes Using Percona Operator

When managing multiple clusters—or seeking hands-off automation—the Percona Operator streamlines kubernetes mysql backup through Custom Resource Definitions (CRDs). Note that this operator targets Percona XtraDB Cluster deployments rather than standalone vanilla MySQL instances.

Automated Backup Configuration

After installing the operator via Helm charts or manifests (kubectl apply ...), configure secrets holding object storage credentials such as AWS S3 keys:

apiVersion : v1 
kind     : Secret 
metadata :
   name      : s3-secret    
   namespace : pxc-cluster-ns    
type     : Opaque    
stringData :
   credentials |-
     [default]
     aws_access_key_id = <YOUR_ACCESS_KEY_ID>
     aws_secret_access_key = <YOUR_SECRET_KEY>
   config |-
     [default]
     region = us-east-1

Define a custom resource manifest specifying both local PVC-based profiles AND remote S3-based profiles:

apiVersion       : pxc.percona.com/v1      
kind             : PerconaXtraDBCluster     
metadata         :
   ...
spec             :
   ...
   backupProfiles :
     - name         : s3-backup-profile        
       dumpInstance :
         storage    :
           s3      :
             bucketName    : my-mysql-backups       
             prefix        : /backups       
             config        : s3-secret        
             profile       : default         
             endpoint      : https://s3.amazonaws.com

Set schedules directly within CRD YAML:

backupSchedules :
   - name               : daily-schedule         
     schedule           :"0 4 * * *"            
     enabled            :'true'                 
     backupProfileName :'s3-backup-profile'

Apply everything using kubectl apply –f manifest.yaml. The operator now manages recurring jobs uploading encrypted compressed archives straight into S3 buckets automatically.

Best Practices

Monitor completed jobs via CR status fields; prune old archives regularly either manually from object storage dashboards OR by setting retention policies within operator configs.

Restoring From Operator Backups

Spin up new clusters referencing previous archive locations via init fields:

initDB                     # points new cluster at existing archive location.

This enables seamless migration across regions/cloud providers—a huge win for disaster recovery planning!

How to Back Up MySQL Workloads in Kubernetes with Vinchin Backup & Recovery

For organizations seeking robust protection beyond manual scripts and open-source tooling, enterprise-level solutions offer advanced features tailored for complex environments. Vinchin Backup & Recovery stands out as a professional platform designed specifically for comprehensive kubernetes mysql backup across diverse infrastructures.

Vinchin Backup & Recovery supports full/incremental backups, fine-grained restore options by cluster/namespace/application/PVC/resource, policy-driven scheduling alongside one-off jobs, secure encryption of both stored and transmitted data, plus cross-cluster and cross-version recovery—including seamless migration between different production environments and cloud platforms—all engineered to maximize reliability while minimizing operational overhead.

Managing kubernetes mysql backups through Vinchin Backup & Recovery’s intuitive web console typically involves four straightforward steps:

Step 1. Select the backup source

Step 2. Choose the backup storage

kubernetes backup

Step 3. Define the backup strategy

kubernetes backup

Step 4. Submit the job

kubernetes backup

Join thousands of global enterprises who trust Vinchin Backup & Recovery—top-rated worldwide—for their mission-critical workloads! Start protecting your data today with a free full-featured trial valid for up to 60 days; click below to download instantly.

FAQs about Kubernetes MySQL Backup

Q1: How do I encrypt my kubernetes mysql backups?

A1: Use built-in encryption options provided by Vinchin; otherwise encrypt SQL dumps before upload using GPG/OpenSSL commands inside CronJobs/pods.

Q2: What should I do if my entire k8s cluster fails?

A2: Redeploy fresh cluster → restore manifests/deployments/services → copy backed-up SQL/data files into new pods/PVCs → run restore commands

Q3: Can I automate offsite transfer of large physical backups?

A3: Yes—install cloud CLI tools (e.g., AWS CLI) inside dedicated transfer pods/jobs then sync /backup folders directly to remote buckets

Conclusion

Kubernetes mysql backup protects business-critical data against loss outages migration risks & compliance gaps whether using native scripts advanced operators—or enterprise solutions like Vinchin which makes protection easy reliable & scalable! Try their free trial today!

Share on:

Categories: Tech Tips