Why back up volumes
Containers come and go, but the data in a Docker volume stays. A volume can still be lost if the disk fails, someone deletes it by mistake, or a move to a new server goes wrong. A backup lets you rebuild the data in minutes.
Back up a volume
The idea: start a small temporary container, attach the volume, and pack its content into a .tar file on the host.
docker run --rm \
-v my_volume:/data \
-v $(pwd):/backup \
alpine tar czf /backup/my_volume.tar.gz -C /data .
my_volumeis the name of your volume. List volumes withdocker volume ls.- The file
my_volume.tar.gzappears in the folder where you ran the command. - The container is deleted after the job (
--rm).
For a database, stop the container first or use the dump tool of the database. This way the backup is complete.
Restore a volume
- Create a new volume:
docker volume create my_volume_restored
- Unpack the archive into it:
docker run --rm \
-v my_volume_restored:/data \
-v $(pwd):/backup \
alpine tar xzf /backup/my_volume.tar.gz -C /data
- Attach the volume to a new or existing container with
-v my_volume_restored:/path/in/container.
Automate it
A hand-made backup is fine for tests. For production, run it on a schedule.
- Put the backup command in a script and run it with cron.
- Add a clean-up step that deletes old archives.
- Many hosting platforms also offer snapshots.
Good habits
- Back up on a fixed schedule.
- Store copies off the server, such as on another host or in cloud storage.
- Test a restore from time to time. A backup you never tested may not work.
Quick recap
- Use a temporary container with
tarto back up a volume. - Restore into a new volume with the same method.
- Automate, keep copies elsewhere, and test.