Module 4 Lesson 4: Volumes and Persistent Storage
Stop losing your data. Learn how to use Docker Volumes and Bind Mounts to ensure your databases and user uploads survive container deletions and upgrades.
Module 4 Lesson 4: Volumes and Persistent Storage
As we learned in Module 2, the "Writable Layer" of a container is temporary. If you run a database inside a container and then delete that container, your data is Deleted forever.
To save data permanently, we use Volumes.
1. Two Ways to Save Data
A. Docker Volumes (Recommended for Databases)
Managed by Docker. You don't know (or care) where they are on your hard drive.
- Pros: Best performance, managed by Docker CLI, easy to backup.
- Syntax:
-v <volume_name>:<container_path>
B. Bind Mounts (Recommended for Development)
Maps a specific folder on your laptop to a folder in the container.
- Pros: You can edit code on your laptop and see it change instantly inside the running container.
- Syntax:
-v /absolute/path/on/host:/container_path
2. Using Volumes in the CLI
# 1. Create a volume
docker volume create my-db-data
# 2. Start a container and "Mount" the volume
docker run -d \
--name my-db \
-v my-db-data:/var/lib/postgresql/data \
postgres
Now, even if you run docker rm -f my-db, the volume my-db-data stays safe. When you start a new container and mount that same volume, all your data is right there.
3. Bind Mounts for Dev Speed
Imagine you are writing a website in Python.
docker run -v $(pwd):/app my-python-app
$(pwd)is a shortcut for "Present Working Directory."- Now, whenever you save your file in your code editor, the file inside the container changes too. No need to
docker buildevery time!
4. Summary Table
| Feature | Docker Volume | Bind Mount |
|---|---|---|
| Location | /var/lib/docker/volumes/ | Anywhere on your host |
| Managed by | Docker | You (The User) |
| Best For... | Databases / Production state | Source Code / Config files |
| Performance | High | Host-dependent |
Exercise: The Survival Test
- Create a volume called
note-taker. - Run an
alpinecontainer and mount that volume:docker run --rm -v note-taker:/data alpine sh -c "echo 'hello from volume' > /data/test.txt"- Note: the
--rmflag means the container is deleted the moment it finishes.
- Note: the
- Now, run a second container and mount the same volume:
docker run --rm -v note-taker:/data alpine cat /data/test.txt - Did you see the message? Why did it survive if the first container was deleted?
- Cleanup: Delete the volume using
docker volume rm note-taker.
Summary
Persistence is what separates "Stateless" apps from "Stateful" apps. By using Volumes for your databases and Bind Mounts for your code, you ensure that your data is safe and your development workflow is fast.
Next Lesson: Configuring on the fly: Environment variables and configuration.