Backups and read-only mounts
How not to lose a volume and how to protect a config from writes.
A volume survives the removal of a container, but not explicit deletion. docker volume rm deletes a volume for good, docker compose down -v deletes the volumes of a whole project, and docker volume prune deletes every volume that no container is attached to right now. The last command is dangerous: a service that was stopped and removed for an update looks unused to it.
A backup of a volume is easy to make with a temporary container that mounts the volume and a host folder and packs the data into an archive:
docker run --rm -v uploads:/data:ro -v "$(pwd)":/backup alpine:3.20 tar czf /backup/uploads.tar.gz -C /data .
The container is removed right after the job, and the archive stays in the current host folder. For databases it is better to use their own dump tools, for example pg_dump, because a copy of a running database's files may turn out inconsistent.
The :ro suffix mounts a volume or folder read-only. The program inside the container can read the files, but any attempt to write ends with an error. Configs, certificates and data the service must not change are mounted this way. In the example above, :ro guarantees that the backup cannot damage the source volume.
docker run -d -v "$(pwd)"/nginx.conf:/etc/nginx/nginx.conf:ro -p 8080:80 nginx:1.27
Here the web server config is mounted from the host read-only: you edit the file on the host and restart the container.
A common mistake is to clean up the disk with docker system prune --volumes on a server that holds data. It deletes every volume without an attached container, and if the database happened to be stopped at that moment, its data is gone. Before any command with prune or -v in it, look at exactly what will be deleted, and keep a fresh backup.
Practice
A dangerous command
Which command deletes the volumes of a Compose project together with the data?
- docker compose stop
- docker compose down
- docker compose down -v
- docker compose restart
Read-only mounts
What is true about the
:rosuffix in-v config:/etc/app:ro? Mark all.- The container can read the files
- Writing to this path ends with an error
- The volume is deleted after the container stops
- It suits configs and certificates
The suffix
Which suffix is added to
-vto mount a volume read-only? Write it with the colon.