9.1.1.3 Compose Shared Volumes
A focused guide to Compose Shared Volumes, connecting core concepts with practical Docker and container operations.
Compose shared volumes are named volumes defined at the Compose file's top level, made available for one or more services to mount, providing the same persistent, independently lifecycled storage a manually created Docker volume would, but declared and managed as part of the overall application definition.
Defining and Using a Shared Volume
A volume is declared under the top-level volumes key, then referenced by name within any service that needs to mount it.
services:
database:
image: postgres:16
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
This declares pgdata as a named volume managed by Compose, mounted into the database service at the expected data directory path.
Sharing the Same Volume Across Multiple Services
A single declared volume can be mounted by more than one service, when those services genuinely need access to the same underlying data.
services:
web:
volumes:
- shared-uploads:/var/www/uploads
processor:
volumes:
- shared-uploads:/data/incoming
volumes:
shared-uploads:
Both web and processor access the identical underlying volume data, despite being entirely separate services.
Volume Persistence Across Compose Lifecycle Commands
A Compose-managed volume persists across docker compose down (which stops and removes containers but, by default, preserves volumes) unless explicitly told to also remove volumes.
docker compose down
docker compose up -d
Data in pgdata remains intact across this down-and-up cycle, since down alone doesn't remove volumes by default.
docker compose down -v
This explicitly removes volumes as well, a more destructive operation that should be used deliberately, not by habit.
Why Compose Shared Volumes Matter
Declaring volumes as part of the overall Compose application definition keeps an application's persistent storage needs clearly documented alongside its services, while still providing the same independent persistence guarantees a manually created named volume would offer outside of Compose.