今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

Docker Volumes vs Bind Mounts: Where Your Data Actually Lives

James Joyner 2026年07月11日 17:38 4 次阅读 来源:Dev.to

A container's writable layer feels like a filesystem, and that's exactly the trap. Write a database into it, remove the container, and the data is gone — no warning, no recovery. If you want anything to survive docker rm , it has to live outside the container, and Docker gives you three ways to do that: named volumes, bind mounts, and tmpfs. Knowing which one to reach for is most of the battle. Why the writable layer betrays you Every running container gets a thin read-write layer stacked on top of its image layers. It looks persistent because you can docker exec in and see your files. But that layer is bound to the container's lifecycle. docker run --name scratch alpine sh -c 'echo hello > /data.txt; cat /data.txt' # hello docker rm scratch # the layer — and /data.txt — no longer exists There's no "oops." The writable layer is discarded with the container. Persistence is not a default you get; it's a decision you make. That decision is a volume, a bind mount, or tmpfs. Named volumes: the default for state A named volume is storage that Docker creates and manages for you. You give it a name, Docker keeps the actual bytes under its own directory, and you never have to care where that is. docker volume create pgdata docker run -d --name db \ --mount type = volume,source = pgdata,target = /var/lib/postgresql/data \ postgres:16 The container writes to /var/lib/postgresql/data , but those bytes land in a Docker-managed location on the host. Remove and recreate the container against the same volume and the data is still there. docker rm -f db docker run -d --name db \ --mount type = volume,source = pgdata,target = /var/lib/postgresql/data \ postgres:16 # same data, new container Where do the bytes actually live? Under Docker's data root, typically /var/lib/docker/volumes/<name>/_data : docker volume inspect pgdata --format '{{ .Mountpoint }}' # /var/lib/docker/volumes/pgdata/_data The point is that you're not supposed to reach into that path directly — Docker owns it. You

本文内容来源于互联网,版权归原作者所有
查看原文