Quiz
Warm-up from lessons 1-2 and 3-2: a running container writes a file. Where does that file live?
Containers forget everything
Lesson 2-3 told you to treat containers as disposable: stop, remove, recreate. But the writable layer is deleted with the container. Run a Postgres database in a container, insert a year of customer records, docker rm it, and the data is gone.
The fix is a volume: a chunk of storage that Docker manages outside any container and mounts into one at a path you choose.
docker volume create dbdata
docker run -d --name db -v dbdata:/var/lib/postgresql/data postgres:16Read -v dbdata:/var/lib/postgresql/data like the -p flag from lesson 2-2: left is the volume name, right is the path inside the container. Postgres writes its files to that path, so they actually land in the volume. Now docker rm -f db and start a fresh container with the same -v flag: all data is still there. The container stays disposable, the data does not.
Bind mounts: a host folder instead
A bind mount is the same flag with a path on the left instead of a name:
docker run -d -v "$(pwd)":/app myapp:v1$(pwd) is your current directory (terminal course), so the container's /app is your project folder, live. Edit a file on your laptop and the container sees the change instantly. That makes bind mounts the standard dev-mode trick: no rebuild per edit.
| Named volume | Bind mount | |
|---|---|---|
Left side of -v | a name (dbdata) | a host path ($(pwd)) |
| Managed by | Docker | you |
| Typical use | database data in production | live source code during development |
Rule of thumb: volumes for data the app owns, bind mounts for files you are editing.
Managing volumes
Volumes are real objects with their own lifecycle, separate from any container:
docker volume ls # every volume on this machine docker volume inspect dbdata # details, including where it lives on the host docker volume rm dbdata # delete it (fails while a container uses it)
Two habits that prevent real losses:
- Name your volumes. If you write
-v /var/lib/postgresql/datawith no name on the left, Docker creates an anonymous volume with a random hash name. The data survives, but three months later nobody knows which of the twelve hash-named volumes holds production data - Deleting is explicit.
docker rmof the container never removes its named volumes. That is the safety you want, but it also means test volumes accumulate until you clean them up (lesson 4-3 covers cleanup)
Quiz
You run Postgres with `-v dbdata:/var/lib/postgresql/data`, then `docker rm -f db`, then start a new container with the same flag. What happens to your data?
Problem
During development you want the container's /app folder to be your live project folder, so edits on your laptop appear instantly inside the container. Is that a named volume or a bind mount?