AI Hints
Home›Docker Tutorial›Build & Store
Docker · Lesson 5 of 8

Volumes: Keep Your Data

Data that survives containers.

⏱ 2 min read▶ Video at 7:09🎓 Free
Watch this lesson in the Docker courseWatch on YouTube ↗Full Docker course

Containers are disposable. When you delete one, everything written inside it is gone. That is great for apps, and terrible for databases. Volumes give containers a place to store data that lives on after the container is removed.

The problem, shown

terminal
docker run --name note alpine sh -c "echo hello > /data.txt"
docker rm note
note
docker run --rm alpine cat /data.txt
cat: can't open '/data.txt': No such file or directory
Each new container starts from the clean image. The file was lost with the old container.

Named volumes

A named volume is storage managed by Docker. Mount it into a container with -v name:/path. Here a Postgres database keeps its data in the pgdata volume, so you can stop, delete and recreate the container without losing a single row.

terminal
docker volume create pgdata
pgdata
docker run -d --name db -e POSTGRES_PASSWORD=secret -v pgdata:/var/lib/postgresql/data postgres:16
5c2d...
docker volume ls
DRIVER    VOLUME NAME
local     pgdata

Bind mounts for development

A bind mount maps a folder from your computer into the container. Edit a file in your editor and the container sees the change instantly, which is perfect while developing.

terminal
docker run -d -p 8080:80 -v "$(pwd)/site:/usr/share/nginx/html:ro" nginx:1.27
e8b1...

Named volume

  • managed by Docker
  • best for databases
  • portable between machines

Bind mount

  • any folder on your computer
  • best for live code editing
  • depends on your file paths

Try it yourself

✍️ Exercise: Prove a volume keeps data

Write a file into a volume from one container, delete it, then read the file from a brand new container.

Show hint

mount the same -v name:/data in both runs

Show solution
terminalbash
docker run --rm -v notes:/data alpine sh -c "echo saved > /data/n.txt"
docker run --rm -v notes:/data alpine cat /data/n.txt
Output
saved

Summary

Key takeaways
  • Container files vanish when the container is removed
  • Named volumes keep data, ideal for databases
  • Bind mounts share a folder for development
Next up: Networking: Connect Your Containers — let containers talk to each other