How to create a back up of a docker data volume

If you are using docker and docker compose to run containered services with persistent storage and you wanted to keep backups off the host machine or offline, then you must have thought about a good solution that works for you. I will discuss the concept of a solution that is simple that worked for me. This is by no mean the best solution for this issue. It can also be used to migrate the container to another host or to transfer container data from one host to another container.

The setup

We have a docker volume called data_volume that is mounted on a path in a running container either with the docker -v volume_name command or with the volumes section in a docker-compose.yml file. Now we want to create a backup of that volume for safe-keeping or for any other purpose.

Creating a backup of a docker volume

We start by stopping the docker container that is using the volume, to ensure no data on the volume will change during the backup process:

sudo docker stop container

Now we mount data_volume to the path /data in a new busybox container that will run a tar cvzf command on the content of the mounted volume, and store the result in a backup.tar.gz file that is also in a mounted volume in the same container, that is mirroring a folder called archived on the host machine.

sudo docker run --rm -v data_volume:/data -v /var/archived:/backup busybox tar -cvzf /backup/backup.tar.gz /data

After the command exists, the container terminates and is removed. In the folder /archived/backup.tar.gz we will find a .tar.gz zipped tar archive of data_volume. We can now copy the file to another machine for safe-keeping or to be used for any other purposes.

scp source_remote:/var/archived/backup.tar.gz target_remote:~/archived/backup.tar.gz

Restoring a docker volume from backup

Let’s say we want to restore that volume. First we create an empty volume

sudo docker volume create data_volume

Then we fill it with data from backup.tar.gz

sudo docker run --rm -v data_volume:/data -v $(pwd)/archived:/backup ubuntu bash -c "cd /data && tar -xvzf /backup/backup.tar.gz --strip 1"

The previous command will run an ubuntu container that will run a bash command that will unzip and unarchive the file backup.tar.gz in the /data folder that is the path on which the newly created volume was mounted.