How to persist data with Docker volumes?
· Category: Docker
Short answer
Docker volumes are the preferred mechanism for persisting data generated by containers. They are managed by Docker, stored outside the container filesystem, and can be shared among multiple containers.
Steps
- Create a volume with
docker volume create. - Mount it with
-v volume:/pathindocker run. - Use named volumes in Docker Compose for declarative management.
Example
docker volume create pgdata
docker run -d --name postgres -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=secret postgres:15
Docker Compose:
services:
db:
image: postgres:15
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
Tips
- Use
docker volume lsto list volumes anddocker volume inspectfor details. - Back up volumes by mounting them in a temporary container and archiving.
- Use volume drivers for remote or cloud-backed storage.
Common issues
- Data loss can occur if you delete a volume without backing it up.
- Anonymous volumes are created automatically but are hard to identify later.
- Permission issues arise when the container user ID does not match the host file owner.