Docker volumes are used to store persistent data separately from your containers. Data that’s kept in a volume remains accessible after your containers stop, allowing you to containerize stateful workloads.
Although volumes outlive containers, this isn’t enough protection for production applications. You should back up your volumes so you can recover them after a disaster. Creating regular volume backups ensures you’re able to restore your environment if your Docker host is compromised or data is accidentally deleted.
Managing Volume Backups
Docker doesn’t have a built-in mechanism for backing up volumes or exporting their contents. You need to set up your own solution to access the volume and copy its data to your backup destination.
Creating a temporary container that mounts the volume you need to back up is usually the easiest way to proceed. Add the --volumes-from
flag to a docker run
command to automatically mount an existing container’s volumes into your backup container. You can then use tools such as tar
and gzip
to deposit an archive of the volume’s content into your working directory.
Here’s a complete example of this technique:
docker run -d --name mysql -v mysql_data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=mysql mysql:8
docker run -it --volumes-from mysql -v D:\workspace\docker\bk:/backup ubuntu tar cvf /backup/backup.tar /var/lib/mysql bash
The --volumes-from
flag means the temporary backup container receives access to the mysql
container’s volumes. The /var/lib/mysql
directory inside the backup container exposes the volume’s content because this is the path used by the mysql
container. Tarring the path will produce an archive of your volume that you can use as a backup. It gets deposited into your working directory because of the bind mount that’s set up by the -v
flag.
The --rm
flag will remove the backup container as soon as the command completes. This leaves the archive in your working directory, ready to be moved to long-term storage. You can automate backup creation by adding the docker run
command as a cron task.