Docker Volume Backup Tutorial

To back up a Docker volume, we can run a temporary container that mounts the volume you want to back up and uses the tar command to create a compressed archive of the volume contents.

docker run --rm \
      -v "$VOLUME_NAME":/backup-volume \
      -v "$(pwd)":/backup \
      busybox \
      tar -zcvf /backup/my-backup.tar.gz /backup-volume

The command at the end creates a compressed tarball (.tar.gz) of the volume contents and saves it to /backup/my-backup.tar.gz

Once the command is executed, you'll find the backup file my-backup.tar.gz in your current working directory.

Restore a Docker Volume

To restore a volume from an existing backup, you can run a container that mounts the target volume and extracts the contents of your backup archive.

docker run --rm \
      -v "$VOLUME_NAME":/restore-volume \
      -v "$(pwd)":/backup \
      busybox \
      tar -xzvf /backup/my-backup.tar.gz -C /restore-volume

The command at the end extracts the contents of the my-backup.tar.gz archive into the target volume /restore-volume.

Automating with Bash Scripts

For easier and repeated backups, we can create a simple bash script that automates the process. There are various scripts available online that simplify this, like vackup by Bret Fisher(https://github.com/BretFisher/docker-vackup). With this kind of script, you can back up and restore volumes with commands like:

./vackup export my-volume backup.tar.gz
./vackup import my-volume backup.tar.gz