BudiBadu Logo
Samplebadu

Docker Compose by Example: Volume Persistence

Compose Specification v2

Managing data persistence with this code example showing named volumes managed by Docker, bind mounts mapping host directories, read-only mount options, and local driver for volume storage.

Code

services:
  db:
    image: postgres:15
    volumes:
      # Named volume (managed by Docker)
      - db-data:/var/lib/postgresql/data
      
  web:
    image: nginx:alpine
    volumes:
      # Bind mount (host path -> container path)
      # Great for development (live reload)
      - ./html:/usr/share/nginx/html
      
      # Read-only bind mount
      - ./config/nginx.conf:/etc/nginx/nginx.conf:ro

# Define named volumes
volumes:
  db-data:
    driver: local

Explanation

Docker containers are inherently ephemeral with data in the writable layer disappearing when containers are removed. Volumes provide persistence mechanisms, with Docker Compose supporting two main types: named volumes and bind mounts. Named volumes are Docker's preferred method for persisting data, managed entirely by Docker and stored in dedicated locations on the host system like /var/lib/docker/volumes/ on Linux.

Volume and bind mount characteristics include:

  • Named volumes are portable, easy to backup, and shareable among multiple containers
  • Bind mounts map specific host files or directories to container locations
  • The local driver is the default volume driver for single-host deployments
  • Read-only mounts with :ro prevent containers from modifying host files
  • Volumes persist data beyond container lifecycle, surviving restarts and removals

Bind mounts are particularly valuable for development environments, mapping source code directories into containers for immediate reflection of host file changes without rebuilding images. The :ro option adds security by preventing containers from modifying mounted configuration files or static assets. Named volumes abstract storage locations, making them ideal for databases, logs, and critical application data requiring persistence across container updates.

Code Breakdown

6
db-data:/var/lib... maps named volume to container path, Docker manages storage location.
13
./html:/usr/share... bind mount maps local html folder to container for live updates.
16
:ro enforces read-only access, container cannot write to nginx.conf.
20
driver: local default driver, stores volume on local Docker host filesystem.