#!/bin/bash # This script backs up all running Docker containers. # For each container, it creates a compressed archive file (.tar.gz) containing # the container's state at the time of execution. # Backups are stored in a directory called "backup_docker_container". # Each backup file is named with the container name and the current date and time, # making it easy to identify when the backup was taken. # # Usage: # 1. Save this script to a file, for example: backup_containers.sh # 2. Make the script executable: chmod +x backup_containers.sh # 3. Run the script: ./backup_containers.sh # # Automation with Cron: # You can automate the execution of this script and manage old backups with a Cron job: # # 1. To back up all Docker containers every Sunday at midnight: # 0 0 * * 0 /root/backup_docker_container.sh # # 2. To delete backup files older than 14 days every day at 1 AM: # 0 1 * * * find /root/backup_docker_container/* -mtime +14 -exec rm {} \; # # Restoring a backup: # To restore a Docker container from a backup, follow these steps: # # 1. Uncompress the .tar.gz file: # gunzip /path/to/backup_docker_container/container_name_date.tar.gz # # 2. Create a Docker image from the .tar file: # cat /path/to/backup_docker_container/container_name_date.tar | docker import - new_image_name # # This will create a new Docker image from the container's backup. # # 3. Start a new container from the restored image: # docker run -d --name new_container_name new_image_name # # This will launch a new container based on the restored image. # # Note: This process does not restore Docker volumes. If your container used volumes, # you will need to restore or recreate them separately. # # This script only backs up running containers at the time of execution. # It exports only the container's file system (container content) and does not back up # Docker volumes that may be mounted from the host. # Backup directory backup_dir="backup_docker_container" # Create backup directory if it doesn't exist mkdir -p "$backup_dir" # Get current date and time current_datetime=$(date +"%Y-%m-%d_%H-%M-%S") # Get list of running Docker containers containers=$(docker ps --format '{{.Names}}') # Iterate through each container and create a compressed backup with container name and current date and time for container in $containers do echo "Backing up container $container..." docker export "$container" | gzip > "$backup_dir/${container}_${current_datetime}.tar.gz" echo "Backup of container $container completed." done # Indicate that the backup process is completed echo "Backup process completed."