Data and networking

Choose volumes or bind mounts

Use named volumes for Docker-managed data and bind mounts when the host must directly provide or edit files.

8 minute lesson

~~~

Volumes and bind mounts both place external storage at a container path, but they serve different workflows.

A named volume is managed by Docker and works well for databases. A bind mount maps an explicit host path and works well for source code during development. A mount hides image files already present at its target path.

docker run --rm -v notes-data:/data alpine sh -c "echo hello > /data/note.txt"
docker run --rm -v notes-data:/data alpine cat /data/note.txt
docker run --rm --mount type=bind,src="$PWD",dst=/work,readonly alpine ls /work

Bind mounts inherit the host path’s existence, permissions, and contents. They can make a development loop fast, but they also couple the container to one machine and can hide files placed at the mount target by the image. A writable bind mount lets the container change host files, so use readonly unless writes are part of the design.

Volumes are more portable across Docker workflows because Docker owns their location, but applications must still handle ownership and backups. Before choosing, ask who owns the data, whether a human must edit it directly, whether the container may write it, and how it will be restored. Those questions lead to a better answer than treating the two mount types as interchangeable syntax.

Persist one file in a volume, then mount the project directory read-only into a different container.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →