Volumes and Storage
Imagine you’re writing notes on a whiteboard. When the meeting ends, the board is wiped clean - all your work is gone. Containers behave the same way: once they stop, their data vanishes. To keep your notes safe, you’d use a notebook. In Docker, that notebook is a volume - a persistent storage mechanism that survives container restarts and removals.
Storage Foundations
1. Why Storage Matters
- Containers are stateless by default - data inside disappears when the container stops.
- Real applications (databases, web apps, logs) need persistent storage.
- Docker provides volumes and bind mounts to solve this problem.
2. Storage Options in Docker
- Volumes:
- Managed by Docker.
- Stored in Docker’s filesystem (
/var/lib/docker/volumes). - Best for portability and isolation.
- Bind Mounts:
- Map a host directory into a container.
- Useful for development (e.g., syncing source code).
- tmpfs Mounts:
- Store data in memory only.
- Fast but non‑persistent.
3. Volumes vs Bind Mounts
| Feature | Volumes | Bind Mounts |
|---|---|---|
| Managed by Docker | ✅ | ❌ |
| Portability | High | Low |
| Use Case | Production data | Development sync |
| Location | Docker filesystem | Host filesystem |
4. Volume Lifecycle
Remove volume:
docker volume rm myvolume
Inspect volume:
docker volume inspect myvolume
Attach to a container:
docker run -d -v myvolume:/data nginx
Create a volume:
docker volume create myvolume
Things to Remember
- Volumes are the recommended way to persist data in Docker.
- Bind mounts are flexible but tightly coupled to the host.
- tmpfs mounts are useful for temporary, high‑speed storage.
Hands‑On Lab
Step 1: Create and Use a Volume
docker volume create datavol
docker run -d --name mydb -v datavol:/var/lib/mysql mysql:latest
- Data is stored in
datavoland persists even if the container is removed.
Step 2: Use a Bind Mount
docker run -d --name web -v $(pwd)/site:/usr/share/nginx/html nginx
- Maps the current directory (
site) into the container’s web root.
Step 3: Inspect Volumes
docker volume ls
docker volume inspect datavol
Step 4: Clean Up
docker rm -f mydb
docker volume rm datavol
Practice Exercise
- Create a volume called
logs. - Run a container that writes logs into
/app/logs. - Stop and remove the container.
- Start a new container using the same volume and confirm the logs persist.
- Compare this with a bind mount by mapping a host directory.
Visual Learning Model
Host Filesystem
↓
Docker Volume (managed by Docker)
↓
Container (mounts volume at /data)
The Hackers Notebook
Volumes and storage solve the ephemeral nature of containers. Volumes are managed by Docker and ideal for production, bind mounts are flexible for development, and tmpfs mounts provide fast in‑memory storage. Mastering these options ensures containers can handle real‑world applications that require persistent data.
