Card 03/ 05

ComparisonDifficulty: Intermediate1 min

Bind Mounts vs Named Volumes

Both keep files after the container is gone; they differ in who owns the files.

A mount connects a directory inside a container to storage outside it, so what the container writes there outlives the container. Docker has two common kinds. A bind mount connects a directory you choose on your own machine. A named volume is storage that Docker creates and manages for you under a name. The table compares them, and the last paragraph says when to use each.

Two ways to keep what a container writes
Compared onBind mountNamed volume
Written as-v /path/on/host:/path/in/container-v mydata:/path/in/container
Where the files areA directory you chose, on this machineA directory Docker manages and you do not name
Who owns the pathYou. It exists whether Docker runs or notDocker. It exists because you asked for a volume
Moves to another machineOnly if that machine has the same pathBy name, with no path to agree on
What it is forFiles you edit on the host and want the container to seeData the container produces and must keep

The row that decides most cases is who owns the path. A bind mount is your directory: you can open it in an editor, and it exists whether Docker is running or not. A named volume belongs to Docker: you refer to it by name, Docker decides where its files live, and it works the same way on any machine.

Use a bind mount when the host is the source of truth, such as your source code during development or a config file you maintain. Use a named volume when the container is the source of truth, which is almost always what a database wants.