✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.2.3 Compose Volumes

A focused guide to Compose Volumes, connecting core concepts with practical Docker and container operations.

The top-level volumes key in a Compose file declares named volumes available for one or more services to mount, providing Compose-managed, persistent storage that's defined and tracked as part of the overall application definition.

Declaring and Using a Volume

A volume is declared by name under the top-level volumes key, then referenced within whichever service needs to mount it.

services:
  db:
    image: postgres:16
    volumes:
      - pgdata:/var/lib/postgresql/data

volumes:
  pgdata:
Why Declaring Volumes at the Top Level Matters

Declaring a volume explicitly, rather than only referencing it inline within a service, makes the volume's existence clear at a glance and allows additional configuration (such as a specific driver) to be applied to it.

volumes:
  pgdata:
    driver: local
Volumes Persist Independently of the Compose Application's Containers

Stopping and removing the containers a Compose application defines doesn't remove its declared volumes by default — their data persists, ready to be reattached the next time the application starts.

docker compose down
docker compose up -d

Data in pgdata survives this down-and-up cycle, since down alone doesn't remove volumes.

Explicitly Removing Volumes When Genuinely Intended

When a complete reset, including all volume data, is actually intended, the -v flag makes this explicit.

docker compose down -v

This more destructive operation should be used deliberately, since it permanently removes the data that would otherwise have persisted.

Why the Volumes Key Matters

Declaring volumes at the Compose file's top level keeps an application's persistent storage needs clearly visible and consistently managed alongside its services, ensuring important data reliably persists across the routine starts, stops, and restarts a Compose-managed application goes through.

Content in this section