Quick and Fast Docker Container Backups.

Quick and Fast Docker Container Backups.

Quick and Fast Docker Container Backups.
  • A quick fast script written by Grok 4 that will stop each container one-at-a-time back it up to a directory named /backup and then start it up again.
#!/bin/bash

# Ensure script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "This script must be run as root"
  exit 1
fi

# Create backup directory if it doesn't exist
BACKUP_DIR="/backup"
mkdir -p "$BACKUP_DIR"

# Get list of running container IDs
containers=$(docker ps -q)

# Check if there are any running containers
if [ -z "$containers" ]; then
  echo "No running containers found"
  exit 0
fi

# Iterate through each container
for container_id in $containers; do
  # Get container name for backup file
  container_name=$(docker inspect --format '{{.Name}}' "$container_id" | sed 's/^\///')
  backup_file="$BACKUP_DIR/${container_name}_$(date +%Y%m%d_%H%M%S).tar"

  echo "Processing container: $container_name ($container_id)"

  # Stop the container
  echo "Stopping container..."
  docker stop "$container_id"

  # Create backup
  echo "Creating backup: $backup_file"
  docker export "$container_id" > "$backup_file"

  # Restart the container
  echo "Restarting container..."
  docker start "$container_id"

  echo "Backup completed for $container_name"
  echo "------------------------"
done

echo "All containers processed"

Good stuff!v - When it runs it will make a log as follows:

And your files will neatly be saved to /backup as in:

Once you have done that it is simply a matter of rsyncing it to another machine and it is easily backed up!

rsync -uvH root@107.152.41.231:/backup/* .
Linux Rocks Every Day