Backup and Restore Docker Volume Data
Here are some scripts that can be used to manually backup and restore data from Docker volumes.
Manual Docker Volume Backup#
This script uses a temporary Docker container to mount the target volume. It also mounts the current directory so it can write the archive file.
Usage: backup-docker-volume.sh <Volume Name> <Backup File Name>
#!/bin/bash
#!/bin/bash
# Usage: backup-docker-volume.sh <Volume Name> [Backup File Name]
# Example 1: ./backup-docker-volume.sh n8n_n8n_data n8n_data_backup
# Example 2: ./backup-docker-volume.sh n8n_n8n_data
# Use this command to find the name of the volume:
# docker inspect --format '{{ json .Mounts }}' <container_name_or_id>
# 1. Capture the volume name
VOLUME_NAME=$1
# 2. Check if the second argument ($2) is provided.
# If not, default to "n8n_backup_" + current timestamp.
TIMESTAMP=$(date +"%Y_%m_%d_%H_%M_%S")
BACKUP_NAME=${2:-"n8n_backup_$TIMESTAMP"}
# 3. Run the backup
docker run --rm \
-v "$VOLUME_NAME":/source:ro \
-v "$(pwd)":/backup \
alpine tar czf /backup/"$BACKUP_NAME".tar.gz -C /source .
echo "Backup completed: ${BACKUP_NAME}.tar.gz"
Restore a Manual Backup#
This script:
- Uses a temporary Docker container to backup the current volume data to a rollback file.
- Uses a temporary Docker container to delete the volume data and restore the data from the specified archive file.
Usage: restore-docker-volume-backup.sh <Volume Name> <Backup File Path>
#!/bin/bash
# Usage: ./restore.sh <Volume Name> <Backup File Path>
VOLUME_NAME=$1
BACKUP_FILE=$2
# 1. Validation
if [ -z "$VOLUME_NAME" ] || [ -z "$BACKUP_FILE" ]; then
echo "Usage: $0 <volume_name> <backup_file_path>"
exit 1
fi
if [ ! -f "$BACKUP_FILE" ]; then
echo "Error: Backup file $BACKUP_FILE not found."
exit 1
fi
# 2. Create Rollback (Safety First)
echo "Creating safety rollback..."
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
docker run --rm -v "$VOLUME_NAME":/source:ro -v "$(pwd)":/backup \
alpine tar czf /backup/rollback_before_restore_$TIMESTAMP.tar.gz -C /source .
# 3. Wipe the volume and Extract the backup in one step
# We mount the current directory to /backup so the container can see the .tar.gz
echo "Restoring data to volume: $VOLUME_NAME..."
docker run --rm \
-v "$VOLUME_NAME":/dest \
-v "$(pwd)":/backup \
alpine sh -c "rm -rf /dest/* && tar xzf /backup/$(basename "$BACKUP_FILE") -C /dest"
if [ $? -eq 0 ]; then
echo "Restore successful!"
else
echo "Restore failed!"
exit 1
fi
This will leave a “rollback” archive file in the current working directory you can use to restore the volume to the “pre-restore” state.
Read other posts