Choose Between Volumes, Bind Mounts and tmpfs
Overview
Docker storage is a set of different mount behaviors. A container's writable layer is temporary, a named volume is Docker-managed persistent storage, a bind mount connects a host path and tmpfs keeps data in memory.
Detailed Notes
Container writable layer
When a container writes a file, Docker normally stores it in the container writable layer. Removing the container removes that layer. Rebuilding or replacing the image does not preserve runtime data.
Named volume
docker volume create app-data
docker run -d --name app -v app-data:/var/lib/app my-app
docker stop app
docker rm app
docker run -d --name app-new -v app-data:/var/lib/app my-app
The second container mounts the same Docker-managed directory. Use named volumes for database files, uploads and any data that must survive container replacement.
Bind mount
docker run --rm -v "$PWD/src:/app/src" my-app
This exposes a specific host directory inside the container. A change on the host is immediately visible to the container. It is useful for development, but the host and container need compatible file ownership and permissions.
tmpfs
docker run --tmpfs /run:rw,noexec,nosuid my-app
Data under /run exists in memory. It disappears when the container stops and is useful for temporary credentials or runtime files, but not persistent database storage.
| Need | Choose |
|---|---|
| Database or uploads survive replacement | Named volume |
| Live source editing | Bind mount |
| Fast temporary data | tmpfs |
| Application image files | No external mount |
Read-only mounts
docker run --mount type=bind,source="$PWD/config",target=/config,readonly nginx
The :ro or readonly option blocks writes through the mount and reduces accidental configuration changes.
Common Interview Questions
Finished this lesson?
0 of 27 lessons done · 0% of the course

