Lately I was in need of backing up Docker volumes, and just like anything else, I searched the Internet on how to do so and did not find concrete articles on how to do it. So, I’ve decided to write an article on how to backup Docker volumes.
This article assumes that you know already how to create docker volumes, attaching them to containers, etc. Only backups will be discussed.
The best way I found to backup a Docker volume is to spawn a container which has the volume mounted, and a external directory exposed. Within the container, I simply perform a tarball of the contents of the volume. So, the sequence of steps to backup volumes are:
- Stop the containers attached to the volumes. This assures no concurrent writing to the volume while you are baking it up. This step, while not mandatory, it’s recommended to avoid consistency issues.
- Spawn a container with the volume and external directory attached to extract the contents into a tarball.
- Destroy the container and restart the actual application containers
Let’s get to work…
Stopping The Containers Attached To The Volumes
Stopping a running container involves invoking the “docker stop” command.
- Gather the container name or container IDs to stop with the command “docker container ls“
- Execute the command “docker stop {container ID|name}” to stop the containers attached to the volumes
Spawn A Container To Do The Backup Operation
In order to simplify the operation, I published a gist written in Bash. The gist is pretty simple, it will backup all the volumes except the auto-generated ones into the /opt/backup directory with a dated tarball. The outlines of the script are:
- The command “docker volume list” is executed and all generated volumes are captured.
- The scripts loops all the volumes, spawns a container which will mount the volume and /opt/backup.
- The container creates the dated tarball into the /opt/backup directory
- The script also cleans up files older than 10 days (the variable backup_retention_days is customizable)
The gist: docker_volume_backup.sh
Clean Up And Restart
The cleanup is performed by the script mentioned above, now all is left to do is to bring the containers back up. In order to do that, the same way you started them before, probably using the “docker run” command.
Now that you have the dated files exported into /opt/backup, you can simply, from an external server, rsync that directory to have an external backup.
I hope now you feel more empowered at backing up Docker containers.
Enjoy and type away!!!