By default, data in a container is ephemeral. If the container is deleted, the data is gone. To persist data (like databases or logs), Docker provides two main methods: Volumes and Bind Mounts.
1. Named Volumes (Recommended)
Volumes are stored in a part of the host filesystem which is managed by Docker (/var/lib/docker/volumes/). This is the best way to persist data in Docker.
Create and Use a Volume
Action:
# Create a named volume
docker volume create my-db-data
# Run a container using that volume
docker run -d --name my-db -v my-db-data:/var/lib/mysql mysql:8Result:
my-db-data
605c77e624dd1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5zInspect the Volume
Action:
docker volume lsResult:
DRIVER VOLUME NAME
local my-db-data2. Bind Mounts
Bind mounts map a specific path on your host machine to a path in the container. This is excellent for development (e.g., live-syncing source code).
Action:
# Map current local directory to /app inside the container
docker run -d --name dev-server -v $(pwd):/app nginxResult: (Any change you make locally to files in $(pwd) will be instantly reflected inside the container)
3. Comparison
| Feature | Named Volume | Bind Mount |
|---|---|---|
| Storage Location | Managed by Docker | Anywhere on host |
| Portability | High (Works across OS) | Low (Host-specific paths) |
| Performance | Excellent | Varies (Can be slow on Mac/Win) |
| Best Use Case | Databases, Production | Local code development |
Summary
- No Volume: Data is lost when container is removed.
- Named Volume: Docker handles where data is stored.
- Bind Mount: You tell Docker exactly where on your disk to store data.