Overview and What You Will Learn
Anything a container writes to its own filesystem is deleted when the container is removed. Docker solves this with three mount types: named volumes (managed by Docker, best for persistent data), bind mounts (a host path mapped into the container, best for development and config files) and tmpfs (RAM only, best for sensitive or throwaway data). Picking the wrong one causes either data loss or fragile deployments.
In this lab you will:
- Persist PostgreSQL data in a named volume and prove it survives container removal
- Use bind mounts safely for development and read-only configuration
- Use tmpfs for temporary secrets and scratch space
- Declare volumes in Docker Compose and back up and restore them without corrupting data
Why This Matters in Production
A database container without a volume is a countdown to data loss: a routine docker rm, an image upgrade or a host reboot with a recreated container wipes everything it wrote. Teams running stateful services on hosts such as mumbai-prod-node-1 treat volumes as the unit of backup, and treat docker compose down -v and docker volume prune as destructive commands that deserve a pause before pressing Enter.
Core Principles
A volume is storage whose lifecycle is separate from any container. You attach it at a path inside the container, and the data stays on the host until you delete the volume explicitly.
pgdata)] F[/Host folder
./src/] R[RAM] end V -->|volume| C([Container]) F -->|bind mount| C R -->|tmpfs| C classDef store fill:#DBEAFE,color:#1E293B classDef app fill:#326CE5,color:#FFFFFF classDef mem fill:#FFEDD5,color:#1E293B class V,F store class C app class R mem
| Type | Use it for |
|---|---|
| Named volume | Databases, uploads, anything that must persist |
| Bind mount | Live code reload, injecting a config file |
| tmpfs | Secrets in use, high-speed scratch, never written to disk |
Named volumes are created and managed by Docker, usually under /var/lib/docker/volumes/, which makes them portable between containers and easy to back up. Bind mounts depend on the exact host path and permissions, which makes them fragile outside development.
Detailed Step-by-Step Practical Lab
Milestone 1: Persist Data with a Named Volume
A named volume keeps data after the container that created it is removed. You will write a table, destroy the container and read the table back from a new one.
docker volume create postgres-datadocker volume inspect postgres-data # Run PostgreSQL with the volume mounted at its data directorydocker run -d \ --name postgres \ -e POSTGRES_PASSWORD=change-me-rahul \ -v postgres-data:/var/lib/postgresql/data \ postgres:15 # Wait for startup, then create datasleep 5docker exec postgres psql -U postgres -c "CREATE TABLE payments (id SERIAL, amount NUMERIC);"docker exec postgres psql -U postgres -c "INSERT INTO payments (amount) VALUES (499.00);" # Destroy the container completelydocker rm -f postgres # The volume is still theredocker volume ls # A new container with the same volume sees the old datadocker run -d \ --name postgres-new \ -e POSTGRES_PASSWORD=change-me-rahul \ -v postgres-data:/var/lib/postgresql/data \ postgres:15sleep 5docker exec postgres-new psql -U postgres -c "SELECT * FROM payments;"Remember
POSTGRES_PASSWORDis only used when the data directory is empty. With an existing volume, the old credentials stay in effect.
Milestone 2: Use Bind Mounts for Development and Config
A bind mount maps a host path into the container, so edits on the host appear instantly inside. Prefer the explicit --mount syntax, because -v silently creates a missing host directory as root, which hides typos.
# Live code reload: host ./src appears at /app/srcdocker run -d \ --name dev-api \ -p 3000:3000 \ --mount type=bind,source="$(pwd)/src",target=/app/src \ node:20-alpine \ node /app/src/server.js # Inject a single config file as read-onlydocker run -d \ --name nginx \ -p 8080:80 \ --mount type=bind,source="$(pwd)/nginx.conf",target=/etc/nginx/nginx.conf,readonly \ nginx:1.25 # Confirm the mountsdocker inspect -f '{{range .Mounts}}{{.Type}} {{.Source}} -> {{.Destination}} (rw={{.RW}}){{"\n"}}{{end}}' nginxWith --mount, a missing source path fails loudly instead of creating an empty directory, which is exactly what you want.
Milestone 3: Use tmpfs for Sensitive or Scratch Data
A tmpfs mount lives in host memory and disappears when the container stops, so sensitive temporary files never touch disk.
# Simple formdocker run -d --name secure-app --tmpfs /tmp alpine:3.20 sleep 3600 # With a size cap and sticky-bit permissionsdocker run -d \ --name api \ --mount type=tmpfs,destination=/tmp,tmpfs-size=104857600,tmpfs-mode=1777 \ alpine:3.20 sleep 3600 # Check it is memory backeddocker exec api df -h /tmpAlways set a size limit, otherwise a runaway process can consume host RAM.
Milestone 4: Declare Volumes in Compose
Compose creates named volumes automatically when you declare them under the top-level volumes: key, and prefixes them with the project name.
# compose.yamlservices: postgres: image: postgres:15 environment: POSTGRES_PASSWORD: change-me-rahul volumes: - postgres-data:/var/lib/postgresql/data api: image: registry.razorpay.in/payment-api:v3.1.0 volumes: - type: bind source: ./config/production.yaml target: /app/config/production.yaml read_only: true - type: tmpfs target: /tmp redis: image: redis:7-alpine volumes: - redis-data:/data volumes: postgres-data: redis-data:docker compose up -ddocker volume ls# local payments_postgres-data# local payments_redis-data # Removes containers and networks, KEEPS volumesdocker compose down # Removes volumes too, destroying all datadocker compose down -vMilestone 5: Back Up and Restore Safely
Copying files from a running database can produce a corrupt backup, so use the database's own dump tool for live data and use a file-level archive only for stopped containers or non-database volumes.
# Logical backup of a running PostgreSQL (consistent, preferred)docker exec postgres-new pg_dump -U postgres -Fc postgres > payments-2026-10-13.dump # File-level backup of a volume (stop the writer first)docker stop postgres-newdocker run --rm \ -v postgres-data:/source:ro \ -v "$(pwd)":/backup \ alpine:3.20 \ tar czf /backup/postgres-data.tar.gz -C /source .docker start postgres-new # Restore the archive into a fresh volumedocker volume create postgres-data-restoreddocker run --rm \ -v postgres-data-restored:/target \ -v "$(pwd)":/backup:ro \ alpine:3.20 \ tar xzf /backup/postgres-data.tar.gz -C /target # Sanity checkdocker run --rm -v postgres-data-restored:/data alpine:3.20 ls /dataMilestone 6: Fix Permission Problems
Permission errors appear when the user inside the container (a numeric UID) does not own the mounted path. Match them rather than running as root.
# Find which UID the app runs asdocker run --rm node:20-alpine id# uid=0(root) ... (the image default), but the app image may switch to uid 1000 # Give a bind-mounted directory to that UID on the hostsudo chown -R 1000:1000 ./uploads # Or tell the container which user to run asdocker run --rm --user 1000:1000 \ --mount type=bind,source="$(pwd)/uploads",target=/app/uploads \ node:20-alpine touch /app/uploads/test.txtProduction Best Practices & Common Pitfalls
- Use named volumes for persistent data in production. Bind mounts tie the container to host paths that can change.
- Back up databases with dump tools. Raw file copies of a live database can be inconsistent.
- Use read-only mounts for config. Add
readonlyor:roso a compromised container cannot rewrite host files. - Treat
docker compose down -vas destructive. It deletes every named volume in the project. - Know that
docker volume prunehas changed. Since Docker Engine 23 it removes only unused anonymous volumes by default, and--allincludes named ones. - Watch for anonymous volumes. A
VOLUMEinstruction in an image creates hash-named volumes that pile up and are hard to identify. - Cap tmpfs size. Memory-backed storage has no disk safety net.
Common MistakeBind mounting the entire application directory in production. A host OS upgrade, permission change or missing path can break the container. Build code into the image and mount only data.
TipRun
docker system df -vto see which volumes exist, how large they are, and which ones no container uses.
SecurityNever bind mount
/var/run/docker.sockor the host root into an application container. Either gives the container effective control of the host.
Quick Reference & Troubleshooting Commands
| Command | Description |
|---|---|
docker volume ls |
List volumes |
docker volume inspect NAME |
Show mountpoint and driver |
docker volume rm NAME |
Delete a volume (fails if in use) |
docker volume prune |
Remove unused anonymous volumes |
docker system df -v |
Show disk use per volume |
docker inspect -f '{{json .Mounts}}' NAME |
List mounts of a container |
| Symptom | Likely cause and fix |
|---|---|
| Data gone after recreate | No volume mounted, add -v name:/path |
permission denied on mount |
UID mismatch, use chown or --user |
| Bind mount is empty dir | Typo created a root-owned folder, use --mount to fail fast |
volume is in use on remove |
Stop and remove the container first |
| Restored DB will not start | Backup taken while running, restore from pg_dump instead |