Module 9 Lesson 5: Backup and Restore Strategies
·DevOps

Module 9 Lesson 5: Backup and Restore Strategies

Protect your data against disasters. Learn the standard patterns for backing up Docker volumes and how to perform a full system recovery from scratch.

Module 9 Lesson 5: Backup and Restore Strategies

Storing data in a volume is the first step. But what if your server's hard drive fails? Or what if you accidentally delete the volume? You need a Backup and Restore strategy.

1. The "Helper Container" Backup Pattern

Since named volumes can be hard to reach from your host OS, the official way to back them up is to start a temporary container that "Mops up" the data into a .tar file.

# Back up 'my_db_volume' to a file named 'backup.tar' in your current local folder
docker run --rm \
  -v my_db_volume:/data \
  -v $(pwd):/backup \
  alpine \
  tar cvf /backup/backup.tar /data

Breakdown:

  1. Mount the volume you want to save to /data.
  2. Mount your current host folder to /backup.
  3. Use the tar command to bundle all files in /data into one file in /backup.

2. The Restore Pattern

To restore, you just reverse the process.

# 1. Create a fresh volume
docker volume create my_fresh_volume

# 2. Extract the backup into the new volume
docker run --rm \
  -v my_fresh_volume:/data \
  -v $(pwd):/backup \
  alpine \
  tar xvf /backup/backup.tar -C /

3. Database-Specific Backups

For databases (Postgres, MySQL, MongoDB), a "File Copy" of the volume while the database is running can lead to corruption.

  • The Proper Way: Use the database's own backup tool (e.g., pg_dump).
  • Example:
    docker exec my-db pg_dumpall -U postgres > full_backup.sql
    

4. Best Practices for Backups

  1. Automate: Put your backup commands into a Cron Job or a GitHub Action so they run every night.
  2. Off-site: Don't keep your backup.tar on the same server as the Docker host! Move it to S3, Dropbox, or a different hard drive.
  3. Test the Restore: A backup you haven't tested is not a backup. Periodically try to start your app from a restored volume to ensure it actually works.

Exercise: The Recovery Drill

  1. Create a volume test-backup and add a text file to it using a container.
  2. Perform a backup of that volume to a test-backup.tar file on your laptop using the command in Section 1.
  3. Delete the volume: docker volume rm test-backup.
  4. Now, recreate the volume and Restore the data from the .tar file.
  5. Verify the file is back.
  6. How would you automate this to run every night at 2:00 AM?

Conclusion of Module 9

You have now mastered Docker Storage. You know how to use named volumes, bind mounts, cloud plugins, and (most importantly) how to recover from a total system failure. Your data is now "Production Grade."

Next Module: Connecting the world: Module 10: Advanced Docker Networking.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn