Backup a Docker volume to tar archive:
$ ./docker-volume-backup.sh \
DOCKER_VOLUME_NAME \
ARCHIVE_NAME.tgz
Restore tar archive into Docker volume:
$ ./docker-volume-backup.sh \
ARCHIVE_NAME.tgz \
DOCKER_VOLUME_NAME
#!/bin/bash -e | |
BACKUP_PATH="/volume-backup" | |
VOLUME_MOUNT_PATH="/data" | |
function exitError { | |
echo "Error: $1" >&2 | |
exit 1 | |
} | |
function main { | |
if [[ -z $1 ]]; then | |
exitError "missing source Docker volume name" | |
fi | |
if [[ -z $(docker volume ls --filter "name=$1" --quiet) ]]; then | |
exitError "unknown Docker volume [$1]" | |
fi | |
if [[ -z $2 ]]; then | |
exitError "missing target archive filename" | |
fi | |
docker run \ | |
--mount "type=bind,src=$(pwd),dst=$BACKUP_PATH" \ | |
--mount "type=volume,src=$1,dst=$VOLUME_MOUNT_PATH" \ | |
--rm \ | |
alpine:latest \ | |
/bin/sh -c "/bin/tar c -zf '$BACKUP_PATH/$2' -C $VOLUME_MOUNT_PATH ." | |
} | |
main "$1" "$2" |
#!/bin/bash -e | |
BACKUP_PATH="/volume-backup" | |
VOLUME_MOUNT_PATH="/data" | |
function exitError { | |
echo "Error: $1" >&2 | |
exit 1 | |
} | |
function main { | |
if [[ -z $1 ]]; then | |
exitError "missing source archive filename" | |
fi | |
if [[ ! -f $1 ]]; then | |
exitError "unable to locate archive [$1]" | |
fi | |
if [[ -z $2 ]]; then | |
exitError "missing target Docker volume name" | |
fi | |
if [[ -n $(docker volume ls --filter "name=$2" --quiet) ]]; then | |
exitError "target Docker volume [$2] already exists" | |
fi | |
docker run \ | |
--mount "type=bind,src=$(pwd),dst=$BACKUP_PATH" \ | |
--mount "type=volume,src=$2,dst=$VOLUME_MOUNT_PATH" \ | |
--rm \ | |
alpine:latest \ | |
/bin/sh -c "cd '$VOLUME_MOUNT_PATH' && tar x -f '$BACKUP_PATH/$1'" | |
} | |
main "$1" "$2" |