Volumes and persistent data
Containers are disposable, but databases, uploads and logs are not. Volumes store data outside a container's writable layer, so it survives restarts, upgrades and removal.
Three kinds of mounts
| Type | Syntax example | Best for |
|---|---|---|
| Named volume | -v pgdata:/var/lib/postgresql/data |
Databases and app data (managed by Docker) |
| Bind mount | -v $(pwd):/app |
Development: live-editing code on your machine |
| tmpfs | --tmpfs /tmp |
Temporary in-memory files, secrets that must not hit disk |
Named volumes: a database that survives
docker volume create pgdata
docker run -d --name db \
-e POSTGRES_PASSWORD=secret \
-v pgdata:/var/lib/postgresql/data \
-p 5432:5432 \
postgres:16
# create some data
docker exec -it db psql -U postgres -c "CREATE TABLE notes(t text); INSERT INTO notes VALUES ('I survive!');"
# destroy the container completely
docker rm -f db
# start a brand-new container with the same volume
docker run -d --name db2 -e POSTGRES_PASSWORD=secret -v pgdata:/var/lib/postgresql/data postgres:16
sleep 3
docker exec -it db2 psql -U postgres -c "SELECT * FROM notes;"The data is still there. ✅
docker volume ls
docker volume inspect pgdata
docker volume rm pgdata # actually deletes the data — careful!How do you know which path to mount? Check the image's documentation on Docker Hub. Postgres uses
/var/lib/postgresql/data, MySQL uses/var/lib/mysql, MongoDB uses/data/db.
Bind mounts: live code reloading
During development, mount your source folder into the container so edits on your machine appear instantly:
docker run -it --rm \
-v "$(pwd)":/app \
-w /app \
-p 3000:3000 \
node:22-alpine \
sh -c "npm install && npx nodemon server.js"Edit server.js in your editor and the server restarts inside the container.
The node_modules gotcha
A bind mount hides whatever was in that folder in the image. If your Mac has macOS node_modules and the container needs Linux ones, add an anonymous volume to protect the container's copy:
-v "$(pwd)":/app -v /app/node_modulesRead-only mounts
docker run -d -v "$(pwd)/nginx.conf":/etc/nginx/nginx.conf:ro nginx:ro makes the mount read-only inside the container. It's a good habit for config files.
Backing up a volume
Volumes are just data, so back them up with a throwaway container:
docker run --rm \
-v pgdata:/data:ro \
-v "$(pwd)":/backup \
alpine tar czf /backup/pgdata-backup.tar.gz -C /data .(For databases, prefer the database's own tool, e.g. pg_dump, for consistent backups.)
Practice
- Create a volume
notes, then runalpinewith it mounted at/dataand write a file into/data. - Remove the container, start a new one with the same volume, and confirm the file exists.
- Serve a local folder with Nginx using a read-only bind mount to
/usr/share/nginx/html.
1.Which mount type should a production database use?
2.What does :ro at the end of a mount mean?