Created
January 16, 2024 07:09
-
-
Save Phate334/284a854d8b66fc6d4d511a0460a2038e to your computer and use it in GitHub Desktop.
Simple script to backup volumes in docker compose env.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Function to get Docker API version | |
get_docker_api_version() { | |
docker version --format '{{.Server.APIVersion}}' | |
} | |
# Function to get volume paths from docker-compose and backup | |
backup_volumes() { | |
# Get the API version | |
API_VERSION=$(get_docker_api_version) | |
echo "Docker API Version: $API_VERSION" | |
# Create a backup directory with the current date | |
BACKUP_DIR="backup-$(date +%Y%m%d)" | |
mkdir -p "$BACKUP_DIR" | |
echo "Backup directory created: $BACKUP_DIR" | |
# Get all container ids from docker-compose | |
container_ids=$(docker-compose ps -q) | |
# Loop through each container | |
for container_id in $container_ids; do | |
# Get container details | |
container_info=$(docker inspect $container_id) | |
# Get volumes from container info | |
volumes=$(echo $container_info | jq -r '.[].Mounts | .[] | select(.Type == "volume") | .Name') | |
# Backup each volume | |
for volume in $volumes; do | |
destination=$(docker inspect $container_id| jq -r --arg volume "$volume" '.[].Mounts[] | select(.Type == "volume" and .Name == $volume) | .Destination') | |
BACKUP_FILE="${volume}_$(date +%Y%m%d%H%M).tar" | |
docker run --rm --volumes-from $container_id -v "$(pwd)/$BACKUP_DIR":/backup ubuntu tar cvf /backup/"$BACKUP_FILE" "$destination" | |
echo "Volume $volume from container $container_id backed up as $BACKUP_FILE" | |
done | |
done | |
} | |
# Check if docker-compose is present | |
if ! command -v docker-compose &> /dev/null | |
then | |
echo "docker-compose could not be found, please install it and run this script again." | |
exit 1 | |
fi | |
# Check if jq is present | |
if ! command -v jq &> /dev/null | |
then | |
echo "jq could not be found, please install it and run this script again." | |
exit 1 | |
fi | |
# Start the backup process | |
backup_volumes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment