How would you back up the data in a Docker volume?
Run a temporary container that mounts the volume and a host folder, then tar the volume contents into the host folder. Restore by extracting that archive into a volume.
Explain it simply
A volume lives inside Docker's own storage area, so you cannot just copy it from your file manager. The trick is to hire a short-term helper container: it sees both the volume and a folder on your laptop, packs the data into a zip, and leaves.
Mount the volume read-only at /data, mount the current host directory at /backup, and run tar czf from one to the other. The helper is deleted with --rm. To restore, do the reverse into a new volume. For databases, a file copy of a running database can be inconsistent, so prefer the database's own tool such as pg_dump or mysqldump, or stop the container briefly first.
Store backups off the machine, for example in cloud storage.
Example
docker run --rm -v pgdata:/data:ro -v "$(pwd)":/backup alpine \
tar czf /backup/pgdata.tar.gz -C /data .
# restore into a fresh volume
docker run --rm -v newdata:/data -v "$(pwd)":/backup alpine \
tar xzf /backup/pgdata.tar.gz -C /dataWhat to say in the interview
"I run a throwaway container that mounts the volume and a host folder and tars the data out. For live databases I prefer pg_dump or mysqldump, or stop the container first, to get a consistent backup."
Common mistakes
- Copying database files while the database is writing and trusting the result.