Data Persistence: Managing Docker Volumes and Bind Mounts
By default, the filesystem inside a running container is temporary. When a container is deleted, any data created or modified inside it is lost. To persist data (like databases or upload folders), Docker uses Volumes and Bind Mounts.
1. Comparing Storage Options
graph TD
A[Docker Storage Models] --> B[Named Volumes: Managed by Docker /var/lib/docker/volumes]
A --> C[Bind Mounts: Mapped directly to specific host folders]- Named Volumes: Docker manages where the volume data is stored on your host machine. They are the recommended way to persist database data (like PostgreSQL or MySQL).
- Bind Mounts: Mapped directly to a specific folder on your host machine. They are useful for local development, allowing you to mount your source code directory so changes are reflected in the container immediately.
2. Using Volumes and Bind Mounts
Mounting Named Volumes
To run a database container and mount a named volume called db-data:
# Mount db-data to the Postgres data storage path
docker run -d -e POSTGRES_PASSWORD=secret -v db-data:/var/lib/postgresql/data postgresMounting Bind Mounts
To map your active project directory into a web server container:
# Map host folder /Users/app to container path /app
docker run -d -p 8080:80 -v /Users/app:/usr/share/nginx/html nginx3. Managing Volumes via CLI
Use these commands to manage volumes on your system:
# Create a named volume
docker volume create uploads-data
# List all volumes
docker volume ls
# Delete a volume
docker volume rm uploads-data
# Delete all unused volumes
docker volume prunePublished on Last updated: