Volumes vs bind mounts — when do you use each, and -v vs --mount?
Take a moment.
Say your answer out loud or write it down first — retrieval is what makes it stick. Reveal when you're ready.
Short answer
Volumes persist container data Docker manages; bind mounts share specific host files/dirs (config, live code) directly into the container. -v /host:/container is terse and auto-creates missing host dirs; --mount type=bind,source=,target= is explicit, errors if the source is missing, and is recommended for production. Append :ro/:rw for permission control.
Detailed explanation
Choose by ownership: generated/modified data that must outlive containers → volume (see Postgres persistence); host-owned files the container must see live → bind mount (config with secrets you refuse to bake into images, or dev code for instant reload). Both attach with -v or --mount: docker run -v /HOST/PATH:/CONTAINER/PATH -it nginx versus docker run --mount type=bind,source=/HOST/PATH,target=/CONTAINER/PATH,readonly nginx. Behavior differs: -v silently mkdirs a missing host path (hiding typos), --mount fails loudly — prefer it for complex/production mounts. Permissions: :ro lets the container read but never modify host files (accident-proof), :rw propagates container writes to the host. The docs' httpd demo shows the power: docker run -d --name my_site -p 8080:80 -v ./:/usr/local/apache2/htdocs/ httpd:2.4, edit local index.html (whale page), and the site updates instantly; delete locally and Desktop's Files tab confirms it vanished inside too. At scale, Synchronized File Shares fix bind-mount slowness between host and VM with filesystem caches.
Official docs:Docker docs: Sharing local files with containers
Example
# Same bind mount, two syntaxes (remove my_site between runs):
docker run -d --name my_site -p 8080:80 -v ./:/usr/local/apache2/htdocs/ httpd:2.4
docker run -d --name my_site -p 8080:80 --mount type=bind,source=./,target=/usr/local/apache2/htdocs/ httpd:2.4
# Guardrails:
docker run -v ~/config:/etc/app:ro nginx # read-only: container cannot alter host
docker run --mount type=bind,source=./,target=/app,readonly nginxInterview tip
Give the decision rule ('volumes for container-owned persistence, binds for host-owned sharing') then contrast -v auto-create vs --mount strictness — that nuance reads as production experience.
Common mistakes
- Baking secrets/config into images instead of bind-mounting or env-injecting them.
- Using
-vwith a relative path typo and wondering where the empty dir came from (use absolute paths, esp. PowerShell).