Skip to content

Storage Management

Docker provides multiple mechanisms for persisting and sharing data between containers, between containers and the host, and across container restarts. This guide covers volumes, bind mounts, tmpfs mounts, and storage best practices.

Storage Types Overview

Docker offers three primary types of storage mounts:

┌──────────────────────────────────────────────────────┐
│                    Container                          │
│                                                      │
│  ┌──────────┐   ┌──────────┐   ┌──────────────┐    │
│  │  Volume   │   │  Bind    │   │    tmpfs      │    │
│  │  Mount    │   │  Mount   │   │    Mount      │    │
│  └────┬─────┘   └────┬─────┘   └──────┬───────┘    │
└───────┼──────────────┼─────────────────┼─────────────┘
        │              │                 │
        ▼              ▼                 ▼
┌──────────────┐ ┌───────────┐   ┌────────────┐
│Docker Area   │ │Host File  │   │  Host RAM  │
│/var/lib/     │ │System     │   │  (memory)  │
│docker/volumes│ │(any path) │   │            │
└──────────────┘ └───────────┘   └────────────┘

Comparison Table

FeatureVolumesBind Mountstmpfs Mounts
Managed by Docker✅ Yes❌ No❌ No
Location on hostDocker-managed pathAny pathMemory only
Survives container removal✅ Yes✅ Yes (on host)❌ No
Can be shared between containers✅ Yes✅ Yes❌ No
Supports volume drivers✅ Yes❌ No❌ No
Pre-populated with image data✅ Yes❌ No❌ No
PerformanceNativeNativeFastest
Recommended forProduction dataDevelopmentSensitive temp data

Docker Volumes

Volumes are the preferred mechanism for persisting data generated by and used by Docker containers.

Creating and Managing Volumes

bash
# Create a named volume
docker volume create my-data

# Create a volume with specific driver and options
docker volume create --driver local \
  --opt type=nfs \
  --opt o=addr=192.168.1.100,rw \
  --opt device=:/path/to/share \
  nfs-volume

# List all volumes
docker volume ls

# Inspect a volume
docker volume inspect my-data

# Remove a specific volume
docker volume rm my-data

# Remove all unused volumes
docker volume prune

# Remove all unused volumes (including anonymous)
docker volume prune --all

Using Volumes with Containers

bash
# Mount a named volume
docker run -d \
  --name db \
  -v my-data:/var/lib/postgresql/data \
  postgres:16

# Using the --mount syntax (more explicit)
docker run -d \
  --name db \
  --mount source=my-data,target=/var/lib/postgresql/data \
  postgres:16

# Mount a volume as read-only
docker run -d \
  --name web \
  -v my-config:/etc/nginx/conf.d:ro \
  nginx:latest

# Anonymous volume (Docker generates a random name)
docker run -d \
  -v /var/lib/data \
  my-app:latest

Volume Mount Syntax Comparison

SyntaxExampleNotes
-v / --volume-v my-vol:/app/dataShorter, traditional syntax
--mount--mount source=my-vol,target=/app/dataMore explicit, recommended

--mount Options

OptionDescriptionExample
typeMount typevolume, bind, tmpfs
sourceVolume name or host pathmy-vol, /host/path
targetContainer path/app/data
readonlyMount as read-onlyreadonly
volume-optVolume driver optionsvolume-opt=size=10G

Bind Mounts

Bind mounts map a file or directory on the host machine to a container path. They are ideal for development workflows.

Using Bind Mounts

bash
# Mount current directory into container
docker run -d \
  --name dev \
  -v $(pwd):/app \
  -w /app \
  node:20 npm start

# Using --mount syntax
docker run -d \
  --name dev \
  --mount type=bind,source=$(pwd),target=/app \
  -w /app \
  node:20 npm start

# Read-only bind mount
docker run -d \
  -v $(pwd)/config:/app/config:ro \
  my-app:latest

# Mount a single file
docker run -d \
  -v $(pwd)/custom.conf:/etc/nginx/nginx.conf:ro \
  nginx:latest

Bind Mount Use Cases

bash
# Development: Live code reloading
docker run -d \
  --name dev-server \
  -p 3000:3000 \
  -v $(pwd)/src:/app/src \
  -v $(pwd)/public:/app/public \
  node:20 npm run dev

# Configuration injection
docker run -d \
  -v /host/config/nginx.conf:/etc/nginx/nginx.conf:ro \
  -v /host/config/ssl:/etc/nginx/ssl:ro \
  nginx:latest

# Log collection
docker run -d \
  -v /var/log/app:/app/logs \
  my-app:latest

tmpfs Mounts

tmpfs mounts store data in the host's memory only. The data is never written to the host filesystem and is removed when the container stops.

bash
# Create a tmpfs mount
docker run -d \
  --name secure-app \
  --tmpfs /app/temp \
  my-app:latest

# Using --mount syntax with size limit
docker run -d \
  --name secure-app \
  --mount type=tmpfs,target=/app/temp,tmpfs-size=100m,tmpfs-mode=1770 \
  my-app:latest

# Multiple tmpfs mounts
docker run -d \
  --tmpfs /app/temp:rw,size=64m \
  --tmpfs /app/cache:rw,size=128m \
  my-app:latest

tmpfs Use Cases

Use CaseDescription
Secret handlingStore secrets that should never touch disk
Temporary filesScratch space that doesn't need persistence
PerformanceHigh-speed I/O for temporary data
SecuritySensitive data that must not persist

Volume Backup and Restore

Backup a Volume

bash
# Backup a volume to a tar file
docker run --rm \
  -v my-data:/source:ro \
  -v $(pwd):/backup \
  alpine:3.19 \
  tar czf /backup/my-data-backup.tar.gz -C /source .

# Backup with a timestamp
docker run --rm \
  -v my-data:/source:ro \
  -v $(pwd):/backup \
  alpine:3.19 \
  tar czf /backup/my-data-$(date +%Y%m%d_%H%M%S).tar.gz -C /source .

Restore a Volume

bash
# Create a new volume
docker volume create my-data-restored

# Restore from backup
docker run --rm \
  -v my-data-restored:/target \
  -v $(pwd):/backup:ro \
  alpine:3.19 \
  tar xzf /backup/my-data-backup.tar.gz -C /target

Copy Data Between Volumes

bash
# Copy data from one volume to another
docker run --rm \
  -v source-vol:/source:ro \
  -v dest-vol:/dest \
  alpine:3.19 \
  cp -a /source/. /dest/

Volumes in Docker Compose

yaml
services:
  db:
    image: postgres:16
    volumes:
      # Named volume for persistent data
      - db-data:/var/lib/postgresql/data
      # Bind mount for initialization scripts
      - ./init-scripts:/docker-entrypoint-initdb.d:ro

  app:
    image: my-app:latest
    volumes:
      # Named volume shared with db
      - uploads:/app/uploads
      # Bind mount for development
      - ./src:/app/src
      # tmpfs for temporary files
      - type: tmpfs
        target: /app/temp
        tmpfs:
          size: 100000000  # 100 MB

  backup:
    image: alpine:3.19
    volumes:
      - db-data:/source:ro
      - ./backups:/backup
    command: tar czf /backup/db-backup.tar.gz -C /source .

volumes:
  db-data:
    driver: local
  uploads:
    driver: local
    driver_opts:
      type: none
      o: bind
      device: /data/uploads

Storage Drivers

Docker uses storage drivers to manage the contents of the image layers and the writable container layer.

Available Storage Drivers

DriverDescriptionRecommended For
overlay2Modern, performant, default on most LinuxAll Linux distributions
fuse-overlayfsOverlay for rootless containersRootless Docker
btrfsUses Btrfs filesystem featuresBtrfs filesystems
zfsUses ZFS filesystem featuresZFS filesystems
vfsNo copy-on-write, uses full copiesTesting only

Configure Storage Driver

json
// /etc/docker/daemon.json
{
  "storage-driver": "overlay2",
  "storage-opts": [
    "overlay2.size=20G"
  ]
}
bash
# Check current storage driver
docker info | grep "Storage Driver"

# Restart Docker after changing storage driver
sudo systemctl restart docker

Storage Best Practices

Do's and Don'ts

✅ Do❌ Don't
Use named volumes for persistent dataStore important data in container's writable layer
Use bind mounts for developmentUse bind mounts in production
Use tmpfs for sensitive temporary dataStore secrets on disk
Backup volumes regularlyAssume volumes are backed up automatically
Use read-only mounts when possibleGive write access when not needed
Clean up unused volumesLet unused volumes accumulate

Monitoring Disk Usage

bash
# View Docker disk usage summary
docker system df

# Detailed disk usage
docker system df -v

# View volume sizes
docker volume ls -q | xargs -I {} sh -c \
  'echo "{}:" && docker run --rm -v {}:/vol alpine du -sh /vol'

# Clean up all unused Docker data
docker system prune --volumes

Next Steps

基于 MIT 许可发布