Persistent Data and Storage
Overview
A container's writable filesystem is normally ephemeral: removing the container removes that writable data. Docker volumes are managed storage outside the container lifecycle. Bind mounts connect a host directory directly into a container and are often useful in development.
Detailed Notes
Create and use a volume
docker volume create postgres-data
docker run -d --name postgres \
-e POSTGRES_PASSWORD=learn \
-v postgres-data:/var/lib/postgresql/data \
postgres:16
postgres-data: Docker-managed volume name:/var/lib/postgresql/data: mount point inside PostgreSQL-e: sets a container environment variable
The database writes to the volume, not only the container filesystem. Removing the container does not remove postgres-data. Remove it explicitly:
docker volume rm postgres-data
Bind mount
docker run --rm -p 8080:80 -v "$PWD/html:/usr/share/nginx/html" nginx:alpine
On macOS/Linux, $PWD means the current directory. Bind mounts provide live access to host files, but permissions and absolute paths differ between operating systems.
Backup a volume
docker run --rm \
-v postgres-data:/source:ro \
-v "$PWD:/backup" \
alpine tar czf /backup/postgres-data.tgz -C /source .
Read-only mounting protects the source during backup. Production databases should use application-aware snapshots or database export tools rather than copying live files.
Volumes and bind mounts outlive the container; tmpfs and writable layers do not.
Common Interview Questions
Finished this lesson?
0 of 27 lessons done · 0% of the course

