Volumes & Bind Mounts
A container's writable layer is deleted together with the container. Anything that must survive (a database's files, uploaded images) or be shared with the host (your source code during development) needs a mount: a directory from outside the container that appears at a path inside it.
| Type | Flag example | Data lives | Typical use |
|---|---|---|---|
| Named volume | -v pgdata:/var/lib/postgresql/data |
in Docker's storage area, managed by Docker | databases, any persistent app data |
| Bind mount | -v "$PWD/src:/app/src" |
a host path you choose | live-editing code, passing config files |
| tmpfs | --tmpfs /tmp |
host memory, gone when the container stops | scratch space, sensitive temporary files |
docker volume create pgdata
docker run -d --name db -e POSTGRES_PASSWORD=dev \
-v pgdata:/var/lib/postgresql/data postgres:17
docker rm -f db # the container is gone...
docker run -d --name db2 -e POSTGRES_PASSWORD=dev \
-v pgdata:/var/lib/postgresql/data postgres:17 # ...but the data is still there
docker volume ls
docker volume inspect pgdataSample output of docker volume inspect pgdata:
[
{
"CreatedAt": "2026-10-17T09:12:44Z",
"Driver": "local",
"Mountpoint": "/var/lib/docker/volumes/pgdata/_data",
"Name": "pgdata",
"Scope": "local"
}
]-v or --mount?
Both create the same mounts. --mount is more verbose but explicit, and it refuses to create a missing host directory for a bind mount (with -v, a typo silently creates an empty folder).
docker run -v pgdata:/data:ro ...
docker run --mount type=volume,source=pgdata,target=/data,readonly ...
docker run --mount type=bind,source="$PWD"/site,target=/usr/share/nginx/html ...
docker run --mount type=tmpfs,target=/tmp,tmpfs-size=64m ...How does Docker tell a volume from a bind mount in -v? If the part before the colon is a path (starts with / or ., or a drive letter on Windows) it is a bind mount; otherwise it is a volume name. No source at all creates an anonymous volume.
def parse_v(spec):
parts = spec.split(":")
options = []
if len(parts) == 1:
source, target = None, parts[0]
else:
source, target, *options = parts
if source is None:
kind = "anonymous volume"
elif source.startswith(("/", "./", "../", "~")):
kind = "bind mount"
else:
kind = "named volume"
mode = "read-only" if "ro" in options else "read-write"
return f"{kind:<16} {source or '(generated id)':<22} -> {target:<28} {mode}"
for spec in ["pgdata:/var/lib/postgresql/data", "./src:/app/src",
"/etc/shop/config.yaml:/app/config.yaml:ro", "/app/node_modules", "cache:/root/.cache"]:
print(parse_v(spec))named volume pgdata -> /var/lib/postgresql/data read-write
bind mount ./src -> /app/src read-write
bind mount /etc/shop/config.yaml -> /app/config.yaml read-only
anonymous volume (generated id) -> /app/node_modules read-write
named volume cache -> /root/.cache read-write
What the container sees
Mounting over a path hides whatever the image had there. But there is one convenience: when an empty named volume is mounted on a path where the image has files, Docker first copies the image's files into the volume. Bind mounts never do that.
image_files = {
"/usr/share/nginx/html": ["index.html", "50x.html"],
"/app/node_modules": ["express/", "pg/"],
}
volumes = {"site": [], "deps": ["old-lib/"]}
host = {"./public": ["home.html", "about.html"], "./empty": []}
def mount(target, source):
if source.startswith("./"):
return host[source] # bind mount: host content wins, always
if not volumes[source]: # empty named volume: seeded from the image
volumes[source] = list(image_files.get(target, []))
return volumes[source]
cases = [
("/usr/share/nginx/html", "site"),
("/usr/share/nginx/html", "./public"),
("/usr/share/nginx/html", "./empty"),
("/app/node_modules", "deps"),
]
for target, source in cases:
print(f"{source:<9} on {target:<22} -> {mount(target, source)}")site on /usr/share/nginx/html -> ['index.html', '50x.html']
./public on /usr/share/nginx/html -> ['home.html', 'about.html']
./empty on /usr/share/nginx/html -> []
deps on /app/node_modules -> ['old-lib/']
Line three is the classic "my site is empty!" surprise: bind-mounting an empty host folder hides the image's files. Line four shows that a volume which already contains data is not refreshed from a newer image; delete it (docker volume rm deps) if you want it re-seeded.
Persistence across containers
volume_store = {}
def run_container(name, mounts, writes):
layer = {}
for path, value in writes.items():
volume = next((v for target, v in mounts.items() if path.startswith(target)), None)
if volume:
volume_store.setdefault(volume, {})[path] = value
else:
layer[path] = value
print(f"{name}: wrote {sorted(writes)}; writable layer kept only until rm")
return layer
run_container("db-v1", {"/var/lib/data": "pgdata"},
{"/var/lib/data/users.tbl": "3 rows", "/tmp/sort.tmp": "scratch"})
# docker rm db-v1 -> the writable layer (with /tmp/sort.tmp) is deleted
print("after rm, volume pgdata holds:", volume_store["pgdata"])
run_container("db-v2", {"/var/lib/data": "pgdata"}, {"/var/lib/data/orders.tbl": "5 rows"})
print("volume pgdata now holds:", sorted(volume_store["pgdata"]))db-v1: wrote ['/tmp/sort.tmp', '/var/lib/data/users.tbl']; writable layer kept only until rm
after rm, volume pgdata holds: {'/var/lib/data/users.tbl': '3 rows'}
db-v2: wrote ['/var/lib/data/orders.tbl']; writable layer kept only until rm
volume pgdata now holds: ['/var/lib/data/orders.tbl', '/var/lib/data/users.tbl']
Practical tips
- Back up a volume by mounting it into a throwaway container:
docker run --rm -v pgdata:/data -v "$PWD":/backup alpine tar czf /backup/pgdata.tgz -C /data . - Permissions on bind mounts: files keep their host UID/GID. If the container runs as UID 10001 and your files belong to UID 1000, writes fail. Match UIDs or use named volumes.
- Performance on macOS/Windows: bind mounts cross the VM boundary and can be slow for folders with many small files (like
node_modules). Keep those in a named volume. - Cleaning up:
docker rm -vremoves a container's anonymous volumes;docker volume pruneremoves unused anonymous volumes (add-ato include named ones). Named volumes are never deleted by accident, which is exactly what you want for a database.
Test yourself
Which -v value creates a bind mount?
- data:/app/data
- /app/data
- ./data:/app/data
- cache:/root/.cache:ro
You bind-mount an empty host folder onto /usr/share/nginx/html. What does nginx serve?
- The image's default index.html
- Nothing: the mount hides the image's files
- A copy of the image's files
- An error page from Docker
You remove a database container with docker rm -f db. What happens to its named volume pgdata?
- It is deleted
- It is kept and can be mounted by a new container
- It becomes read-only
- It is moved into the image