Lesson 1: The Vault (Persistent Data with Volumes)
Here's a terrifying fact: when a container is deleted, all its data is lost. If you're running a database in a container and you remove it — poof, all your data is gone. Volumes fix this.
The Data Problem
Container lifecycle:
docker run → Container runs → Writes data → docker rm → 💀 DATA GONE
With a volume:
docker run -v data:/db → Container runs → Writes to volume → docker rm → 📦 DATA SAFE
What is a Volume?
A volume is a persistent storage area managed by Docker that exists independently of any container. Even if you delete the container, the volume survives.
Types of Storage
| Type | Syntax | Use Case |
|------|--------|----------|
| Named Volume | -v mydata:/app/data | Production data (databases) |
| Bind Mount | -v /host/path:/container/path | Development (live code editing) |
| tmpfs | --tmpfs /tmp | Temporary data in memory |
Named Volumes (Recommended for Production)
# Create a volume
docker volume create app-data
# Use it with a container
docker run -d -v app-data:/var/lib/postgresql/data postgres
# The data persists even after the container is removed!
docker rm -f postgres_container
docker run -d -v app-data:/var/lib/postgresql/data postgres
# ✅ Your data is still there!
Bind Mounts (Great for Development)
Bind mounts link a host directory directly into the container. Changes on either side are instantly reflected:
docker run -d -v $(pwd)/src:/app/src -p 3000:3000 node-app
This is perfect for development — edit code on your laptop, and it's instantly updated inside the container.
Volume Management
docker volume ls # List all volumes
docker volume inspect app-data # View volume details
docker volume rm app-data # Remove a volume
docker volume prune # Remove ALL unused volumes
Read-Only Mounts
For security, you can mount volumes as read-only:
docker run -v config:/app/config:ro nginx
The container can read the config but cannot modify it.
Mission Objective
Set up persistent storage:
- Create the vault: Run
docker volume create app-data. - Use it: Run
docker run -d --name db -v app-data:/var/lib/postgresql/data postgres:alpine. - Inspect: Run
docker volume inspect app-datato see where it's stored.