You can use a similar technique to restore your backup. When you’re replacing the contents of an existing volume, create another temporary container with the volume and a bind mount to your backup archive. Extract the contents of the archive into the volume’s mount path.
$ docker run --rm \ --volumes-from mysql -v $PWD:/backup-dir bash -c "cd /var/lib/mysql && tar xvf /backup-dir/mysql-backup.tar"
This can be risky if containers are actively using the volume. Overwriting files that are in use could cause errors and unexpected behavior. You can use the
docker stop command to temporarily halt your containers before bringing them back up with
$ docker stop mysql # Restore the backup # ... $ docker start mysql
Create the volume before you start your container if you’re restoring a backup to a new host:
$ docker volume create new_volume
Then mount this volume to your temporary container:
docker run --rm \ -v new_volume:/var/lib/mysql -v $PWD:/backup-dir \ ubuntu tar cvf /backup-dir/mysql-backup.tar /var/lib/mysql
Starting your application container with the same volume will provide access to the files you’ve restored:
docker run -d \ --name mysql \ -v new_volume:/var/lib/mysql \ -e MYSQL_ROOT_PASSWORD=mysql \ mysql:8
Testing these procedures lets you check your backups will be usable if you ever face a disaster.
Backing Up Volumes Directly
The procedure outlined above is the recommended way to back up Docker volumes. However some situations could be better served by directly copying content from where volumes are stored on your host’s filesystem.
You’ll usually find the content of your volumes in
/var/lib/docker/volumes. Each volume gets its own subdirectory, such as
/var/lib/docker/volumes/mysql. Within this top-level path you’ll find a
_data folder which contains all the files stored inside the volume.
/var/lib/docker/volumes directory can be a convenient way to quickly backup everything on your host. You’ll need to use
sudo though because everything under this path is owned by
Backing up volumes in this way isn’t recommended for regular use because it’s not portable across installations. Docker’s volume driver system means volume data won’t necessarily be stored on your host’s filesystem – it could be on a network share or another remote location. This technique should only be attempted when you want a quick backup before you run maintenance on a specific machine.