Docker
Volumes & Bind Mounts
Persist data with named volumes, anonymous volumes, and bind mounts.
By EZ4Code Team
volumepersistencestorage
Code
# Create and list named volumes
docker volume create pgdata
docker volume ls
docker volume inspect pgdata
# Mount a named volume
docker run -d --name db -v pgdata:/var/lib/postgresql/data postgres:16
# Bind mount a host directory (read-only flag supported)
docker run -v $(pwd)/config:/etc/app:ro myapp
# Remove unused volumes
docker volume prune
# Copy files between host and container
docker cp ./dump.sql db:/tmp/dump.sql
docker cp db:/var/log/app.log ./app.logExplanation
Named volumes are managed by Docker and survive container removal, making them ideal for databases. Bind mounts mount a host path directly and are great for live editing during development. docker cp copies files between the host and a running container.
More Docker Snippets
Run a Container
Run, list, stop, and remove Docker containers.
Writing a Dockerfile
Build an image from a Dockerfile with multi-instruction layers.
Image Management
Pull, list, tag, push, and prune images.
Networking
Create networks, attach containers, and expose ports.
Docker Compose
Define and run multi-container apps with compose.
Multi-Stage Build
Build artifacts in one stage and copy them into a slim final image.