You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Containers are ephemeral by design: when a container is removed, its writable layer — and any data written to it — is gone. Volumes are the mechanism Docker provides for persisting data beyond the lifetime of a container and for sharing data between containers.
Consider a database container. Every time you restart the container the database starts fresh unless you persist the data directory somewhere outside the container's writable layer. Volumes solve this by mounting a directory from outside the container into its filesystem.
There are three types of storage in Docker:
Named volumes are the recommended way to persist data in production. Docker manages where the data is stored on disk; you refer to the volume by name.
# Create a named volume
docker volume create my-data
# Run a container with the volume mounted at /data
docker run -d --name my-app -v my-data:/data my-image
# List volumes
docker volume ls
# Inspect a volume (shows mount point on host)
docker volume inspect my-data
# Remove a volume (only if no containers are using it)
docker volume rm my-data
# Remove all unused volumes
docker volume prune
Bind mounts map a specific path on the host filesystem into the container. They are especially useful during development because changes you make to files on your host are immediately visible inside the container.
# Mount the current directory into /app inside the container
docker run --rm -it -v $(pwd):/app -w /app node:20-alpine sh
# The -v flag syntax: host-path:container-path
docker run -d -v /host/config:/etc/myapp/config:ro my-image
The :ro suffix makes the bind mount read-only inside the container, which prevents the container from accidentally modifying host files.
# Run PostgreSQL with a named volume for data persistence
docker run -d --name postgres -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=mydb -v postgres-data:/var/lib/postgresql/data -p 5432:5432 postgres:16
# Stop and remove the container
docker stop postgres
docker rm postgres
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.