SyntaxStudy
Sign Up
Docker Volume Drivers and Sharing Data Between Containers
Docker Beginner 1 min read

Volume Drivers and Sharing Data Between Containers

Docker's volume driver system allows volumes to be backed by external storage: NFS shares, AWS EBS or EFS, Azure File Storage, Ceph, GlusterFS, and more. The driver is specified when creating the volume. This enables multiple containers on different hosts to share the same volume, which is essential for stateful services in a Swarm cluster. Sharing a volume between containers is done by mounting the same named volume in both docker run commands. This is the mechanism for a web server container to serve files written by an application container, or for a log aggregator container to read logs written by the application. Concurrent writes to shared volumes require the application to handle locking — Docker provides no coordination layer. Volume mounts in Dockerfile via the VOLUME instruction declare intent but do not create named volumes at build time. At runtime, Docker creates an anonymous volume (with a generated name) if no explicit -v is provided. Anonymous volumes are inconvenient to manage; always prefer naming volumes explicitly in docker run or docker-compose.yml.
Example
# Share a volume between two containers
docker volume create shared-uploads

# App container writes files to the volume
docker run -d \
  --name app \
  -v shared-uploads:/app/uploads \
  myapp:latest

# Nginx container serves the same files (read-only)
docker run -d \
  --name nginx \
  -p 80:80 \
  -v shared-uploads:/usr/share/nginx/html/uploads:ro \
  nginx:alpine

# NFS-backed volume for multi-host sharing
docker volume create \
  --driver local \
  --opt type=nfs \
  --opt o=addr=192.168.1.100,rw,vers=4 \
  --opt device=:/exports/appdata \
  nfs-appdata

docker run -d -v nfs-appdata:/data myapp:latest

# List anonymous vs named volumes
docker volume ls --filter "dangling=true"
docker volume ls --filter "name=pgdata"

# Remove unused volumes
docker volume prune -f
docker volume rm pgdata