Skip to content

Instantly share code, notes, and snippets.

@rakheshster
Last active August 25, 2020 13:56
Show Gist options
  • Save rakheshster/bacfd78d5ca937576a4d0f7f893bc0d1 to your computer and use it in GitHub Desktop.
Save rakheshster/bacfd78d5ca937576a4d0f7f893bc0d1 to your computer and use it in GitHub Desktop.
Backup the Docker volumes of all running containers. This requires 'jq'. Currently it uses some Bashisms but can be easily changes for others shells I imagine.
#!/bin/bash
BACKUPFOLDER="/opt/backups"
TIMESTAMP=$(date '+%Y-%m-%d')
if ! command -v jq &> /dev/null; then echo "Cannot find jq. Exiting ..."; exit 1; fi
# Get list of running containers
CONTAINERS=( $(docker ps --format '{{.Names}}') )
# Process each container
for CONTAINER in "${CONTAINERS[@]}"; do
echo "Processing $CONTAINER"
VOLUMES=( $(docker inspect $CONTAINER | jq '.[] | .Mounts | .[] | select(.Type == "volume") | .Name') )
# explaining the jq script:
# .[] - take the given input as an array
# .Mounts - get the "Mounts" element
# .[] - the "Mounts" element is an array, so treat it thus and pipe out to the next step
# select(.Type == "volume") - select just the mounts that have a type of "volume"
# Process each volume in the container
for VOL in "${VOLUMES[@]}"; do
# Strip out the " characters from the volume name
VOL=${VOL//\"}
echo "...Processing $VOL"
# Run an alpine container that will be removed later. Into this I mount the volume and also a location to backup to.
# I then run a tar command to backup the volume to this location.
docker run --rm -v $VOL:/$VOL -v $BACKUPFOLDER:/backup alpine tar czf /backup/$TIMESTAMP-$CONTAINER-$VOL.tgz -C / $VOL
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment