9.2.3.5 Compose Persistent Data
A focused guide to Compose Persistent Data, connecting core concepts with practical Docker and container operations.
Compose persistent data refers to the overall practice of ensuring an application's important data survives the routine starts, stops, and recreations a Compose-managed application goes through, by correctly using declared named volumes for every service whose data genuinely needs this durability.
Identifying What Data Within a Compose Application Needs Persistence
Each service should be evaluated individually for whether its data needs to survive beyond that service's current running instance, with named volumes applied specifically to the services and paths where this is genuinely needed.
services:
db:
image: postgres:16
volumes:
- pgdata:/var/lib/postgresql/data
cache:
image: redis:7
api:
build: .
volumes:
pgdata:
Here, only db has a declared, persistent volume, reflecting that its data genuinely needs to survive, while cache and api have no equivalent persistence need.
Verifying Persistence Actually Works as Expected
Testing that data survives a full application teardown and restart (short of an explicit volume removal) confirms the persistence configuration is correctly in place.
docker compose up -d
docker compose exec db psql -c "INSERT INTO test VALUES ('check')"
docker compose down
docker compose up -d
docker compose exec db psql -c "SELECT * FROM test"
The inserted row remains present after this down-and-up cycle, confirming pgdata's persistence is working correctly.
Combining Persistence With a Backup Strategy
Volume-based persistence alone protects against container and application-level teardown, but not against host failure or volume deletion — a complete approach to data durability also includes a tested backup process for this same data.
docker run --rm -v myapp_pgdata:/data:ro -v $(pwd)/backups:/backup alpine tar czf /backup/db-backup.tar.gz -C /data .
Why Compose Persistent Data Matters
Deliberately ensuring the right services have the right persistent volumes declared, and verifying that persistence actually behaves as expected, is essential for any Compose application managing data that genuinely cannot afford to be lost during normal application lifecycle operations.