Volumes and Storage
Containers are ephemeral: when you remove a container, changes inside its filesystem are lost. Volumes and bind mounts give you persistent or host-linked storage.
Volume (Named Volume)
Section titled “Volume (Named Volume)”A named volume is managed by Docker. Data lives in a directory on the host (often under /var/lib/docker/volumes/) and survives container removal. Best for databases and other data that should persist.
# Create a named volumedocker volume create mydata
# Use it in a containerdocker run -d -v mydata:/var/lib/mysql mysql:8
# Inspectdocker volume lsdocker volume inspect mydataIn Compose:
services: db: image: postgres:16-alpine volumes: - dbdata:/var/lib/postgresql/datavolumes: dbdata:Bind Mount
Section titled “Bind Mount”A bind mount maps a host path into the container. Changes are visible on both sides. Good for config files, source code during development, or when you need direct access to host files.
# Mount host ./app into container /appdocker run -v $(pwd)/app:/app myapp:1.0In Compose:
volumes: - ./config:/app/config:ro # :ro = read-only in containertmpfs Mount
Section titled “tmpfs Mount”tmpfs is in-memory storage. Nothing is written to disk; it disappears when the container stops. Use for sensitive or temporary data (e.g. secrets, scratch space).
docker run -d --tmpfs /tmp:rw,size=100m myapp:1.0Comparison
Section titled “Comparison”| Type | Managed by | Persists after container rm? | Use case |
|---|---|---|---|
| Named volume | Docker | Yes (until volume rm) | DB data, persistent app data |
| Bind mount | Host path | Yes (host filesystem) | Config, source in dev |
| tmpfs | Memory | No | Temp or sensitive data |
Commands
Section titled “Commands”docker volume create <name>docker volume lsdocker volume inspect <name>docker volume rm <name>docker volume prune # Remove unused volumesKey Takeaways
Section titled “Key Takeaways”- Named volumes — Docker-managed, persistent; ideal for databases and app data.
- Bind mounts — Host path mapped in; good for config and dev source.
- tmpfs — In-memory; no persistence. Use docker volume commands to manage named volumes.