Skip to content

Nuface Blog

隨意隨手記 Casual Notes

Menu
  • Home
  • About
  • Services
  • Blog
  • Contact
  • Privacy Policy
  • Login
Menu

Docker + MariaDB Backup and Restore Best Practices

Posted on 2025-11-052025-11-05 by Rico

This post summarizes best practices for backing up and restoring MariaDB databases running inside Docker containers.
It explains different backup strategies, practical command examples, and key considerations to ensure data reliability and consistency in containerized environments.


1. Why Backups Matter for Dockerized Databases

When MariaDB runs inside Docker, the actual data resides in volumes or bind-mounted directories on the host system.
If a container is removed or rebuilt without preserving these volumes, all database data will be lost.

📌 The key to safe backups in Docker:

Always back up the persistent storage layer and ensure data consistency during the process.


2. Three Common Backup Methods

MethodDescriptionSuitable For
Logical backup (mysqldump)Exports schema and data as SQLMost reliable, cross-version compatible
Physical backup (volume copy)Copies /var/lib/mysql data directoryFast, but version-dependent and requires downtime
Automated dump (cron + mysqldump)Scheduled dump inside or outside containerBest for daily automated backups

3. Logical Backup with mysqldump

This is the safest and most portable method.

🔹 Manual Export

docker exec -i mariadb \
  mysqldump -u root -p'abcd123' --single-transaction --quick \
  --routines --events --triggers --default-character-set=utf8 \
  nuface | gzip > /backup/nuface_$(date +%F).sql.gz

Key options explained:

  • --single-transaction: Ensures consistency without locking (for InnoDB)
  • --quick: Streams rows to reduce memory usage
  • --routines, --events, --triggers: Include all database logic
  • --default-character-set=utf8: Prevent encoding issues
  • gzip: Compresses the dump file to save space

4. Automating Backups with Cron

1️⃣ Create a backup script /usr/local/bin/backup.sh

#!/bin/bash
DATE=$(date +%F)
docker exec -i mariadb \
  mysqldump -u root -p'abcd123' --single-transaction --quick \
  --routines --events --triggers --default-character-set=utf8 \
  nuface | gzip > /backup/nuface_$DATE.sql.gz

# Remove old backups (keep last 7 days)
find /backup -name "nuface_*.sql.gz" -mtime +7 -delete

2️⃣ Add a cron job

0 2 * * * /usr/local/bin/backup.sh >> /var/log/mariadb_backup.log 2>&1

📌 Recommended time: 2 AM (low traffic)
📦 Retention period: Keep the last 7–30 days depending on policy


5. Physical Backup (Volumes or Bind Mounts)

If your MariaDB container stores data in /data/mysql on the host:

docker run -d \
  --name mariadb \
  -v /data/mysql:/var/lib/mysql \
  -e MARIADB_ROOT_PASSWORD=abcd123 \
  mariadb:12.1

🔹 Backup procedure:

systemctl stop docker
cp -a /data/mysql /backup/mysql_$(date +%F)
systemctl start docker

⚠️ Notes:

  • Must stop MariaDB or Docker to prevent corruption.
  • Restores only work with the same MariaDB version.
  • Not recommended for live production databases due to downtime.

6. Restoring from SQL Dumps

Restore uncompressed .sql

docker exec -i mariadb \
  mariadb -u root -p'abcd123' nuface < /backup/nuface_2025-09-16.sql

Restore compressed .sql.gz

gunzip -c /backup/nuface_2025-09-16.sql.gz | \
docker exec -i mariadb \
  mariadb -u root -p'abcd123' nuface

📌 If your dump includes CREATE DATABASE and USE statements, the database name can be omitted.


7. Restoring from Volume Backups

If your backup is stored at /backup/mysql_2025-09-16:

systemctl stop docker
rm -rf /data/mysql/*
cp -a /backup/mysql_2025-09-16/* /data/mysql/
systemctl start docker

Or using Docker volumes:

docker run --rm -v mariadb_data:/var/lib/mysql -v /backup:/backup busybox \
  sh -c "cd /var/lib/mysql && tar xvf /backup/mysql_backup.tar"

8. Data Consistency and Hot Backup Tips

EngineRecommended ActionNotes
InnoDBUse --single-transactionSafe for online (hot) backups
MyISAMUse FLUSH TABLES WITH READ LOCK;Prevents inconsistencies
Multiple databasesUse --all-databasesEnsures schema alignment
Large databasesAdd --max-allowed-packet=512MPrevent packet size errors

9. Verifying Backup Integrity

A backup is only useful if it can be restored successfully.

Basic validation:

gunzip -t /backup/nuface_2025-09-16.sql.gz   # Verify gzip file integrity
head /backup/nuface_2025-09-16.sql.gz        # Check file header

Test restore in a sandbox container:

docker exec -i testdb \
  mariadb -u root -p'abcd123' testdb < /backup/nuface_2025-09-16.sql

10. Backup & Restore Best Practices Summary

AspectRecommendation
Export methodUse mysqldump + gzip
AutomationRun daily backups with cron
RetentionKeep 7–30 days of backups
Restore testingValidate monthly in a test environment
SecurityUse MYSQL_PWD to avoid exposing passwords
ConsistencyAlways use --single-transaction for InnoDB
CompressionPrefer .sql.gz or .tar.gz for storage efficiency

11. Example: Complete Automated Backup Structure

/backup/
├── backup.sh
├── nuface_2025-09-16.sql.gz
├── nuface_2025-09-17.sql.gz
└── logs/
    └── mariadb_backup.log

Each nightly job performs:

  1. Database export via mysqldump
  2. Compression (gzip)
  3. Automatic cleanup of old files
  4. Log entry creation for audit tracking

12. Conclusion

In Dockerized environments, data persistence and backup strategy are critical to reliable operations.
Regardless of your approach, follow these three golden rules:

  1. Automate backups – never rely on manual dumps
  2. Validate restores – a backup is only useful if it works
  3. Ensure version consistency – use the same MariaDB version for restore

By following these principles, you can restore services quickly and confidently even in the event of container or host failure.


📎 Related Reading

  • 🧱 mysqldump Export Syntax Notes (MySQL / MariaDB 5.5)
  • 🐬 Importing MariaDB SQL Files Inside Docker Containers — Practical Notes
  • MariaDB Official Docs: Backup and Restore

Recent Posts

  • Enable Logrotate for Dovecot in Docker: Prevent Huge Log Files and Disk Overflow
  • 在 Docker Dovecot 中啟用 Logrotate:避免 log 爆量、磁碟被塞滿的最佳做法
  • How to Choose Suricata RuleSets on OPNsense — Practical Guide & Best Recommendations
  • OPNsense Suricata 使用指南 — 規則(RuleSets)該怎麼選?最佳實務與推薦設定
  • Proxmox VE + Proxmox Backup Server Integration & Cross-Node Restore Guide

Recent Comments

No comments to show.

Archives

  • November 2025
  • October 2025

Categories

  • AI
  • Apache
  • Cybersecurity
  • Database
  • DNS
  • Docker
  • Fail2Ban
  • FileSystem
  • Firewall
  • Linux
  • LLM
  • Mail
  • N8N
  • OpenLdap
  • OPNsense
  • PHP
  • QoS
  • Samba
  • Switch
  • Virtualization
  • VPN
  • WordPress
© 2025 Nuface Blog | Powered by Superbs Personal Blog theme