Skip to content

Instantly share code, notes, and snippets.

@magnetikonline
Last active April 18, 2024 23:50
Show Gist options
  • Save magnetikonline/ebd03bddefa7270440605ada42e6a0cc to your computer and use it in GitHub Desktop.
Save magnetikonline/ebd03bddefa7270440605ada42e6a0cc to your computer and use it in GitHub Desktop.
Docker volume backup and restore scripts.

Docker volume backup and restore scripts

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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment