Volumes for data that must survive
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's database lives in a container. Remove the container and every order and customer disappears with it. Data that must survive has to live somewhere else.
A container's own files disappear with the container
A writable layer is the thin layer on top of a read-only image where a container keeps the files it creates or changes. docker stop and docker start keep it; docker rm deletes it.
Write a file inside a container, remove the container, and see what is left. Then the same story in Java, with a folder standing in for the container.
Example 1 · Write a file, remove the container, the file is gone
Runs in: a terminal with Docker installed
docker run --name notes-1 eclipse-temurin:25-jre sh -c 'mkdir -p /data && echo "fees paid on 5 June" > /data/notes.txt && cat /data/notes.txt'docker rm notes-1docker run --rm --name notes-2 eclipse-temurin:25-jre cat /data/notes.txtfees paid on 5 June notes-1 cat: /data/notes.txt: No such file or directory
What this code does
notes-1wrote the file into its own writable layer and printed it.docker rm notes-1deleted that layer, file included.notes-2starts from the same image, which never had/data/notes.txt, socatfails. Nothing is shared between the two containers.
Example 2 · The same story in Java: a layer vs a volume
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;import java.util.Comparator;import java.util.stream.Stream;
public class ContainerLayerDemo { // A "container" here is just a folder that is thrown away on docker rm static Path runContainer(Path root, String name) throws IOException { return Files.createDirectories(root.resolve(name)); }
static void removeContainer(Path container) throws IOException { try (Stream<Path> files = Files.walk(container)) { files.sorted(Comparator.reverseOrder()).forEach(p -> p.toFile().delete()); } }
public static void main(String[] args) throws IOException { Path root = Files.createTempDirectory("docker-sim"); Path volume = Files.createDirectories(root.resolve("volume-notes-data"));
Path first = runContainer(root, "container-1"); Files.writeString(first.resolve("notes.txt"), "fees paid on 5 June"); Files.writeString(volume.resolve("notes.txt"), "fees paid on 5 June"); System.out.println("container-1 wrote notes.txt in its own layer and in the volume");
removeContainer(first); System.out.println("docker rm container-1");
Path second = runContainer(root, "container-2"); System.out.println("container-2 layer has notes.txt? " + Files.exists(second.resolve("notes.txt"))); System.out.println("volume has notes.txt? " + Files.exists(volume.resolve("notes.txt"))); System.out.println("volume content: " + Files.readString(volume.resolve("notes.txt")));
removeContainer(root); }}container-1 wrote notes.txt in its own layer and in the volume docker rm container-1 container-2 layer has notes.txt? false volume has notes.txt? true volume content: fees paid on 5 June
What this code does
- A simplified model: each container's writable layer is a folder that
removeContainerdeletes, likedocker rm. The volume is a separate folder that no container owns. - The new container's layer is empty, but the volume still has the note. All folders live in a temp directory that the program deletes at the end.
A new container from the same image starts with a clean copy, so nothing is shared between containers.
That is fine for temporary files. It is a disaster for a database: remove and recreate a MySQL container without a volume, and every ShopLite order and customer is gone.
Predict the output
Is the file still there?
The container shop wrote /data/a.txt in its own layer. Pick the result.
Round 1 of 2
After a stop and a start.
Named volumes, bind mounts and tmpfs
A named volume is storage that Docker creates and manages for you under a name such as shoplite-data. It lives outside the container, so it survives docker rm.
Docker has three ways to store files outside the writable layer. Each uses a flag with a target path inside the container.
# named volume: Docker manages the storagedocker run -d --name shoplite-db -v shoplite-data:/var/lib/mysql --env-file db.env -p 3307:3306 mysql:8.4# bind mount: the src folder of this project, seen as /app/src insidedocker run --rm -v ./src:/app/src -w /app eclipse-temurin:25-jdk ls src# tmpfs: in memory only, gone when the container stopsdocker run --rm --tmpfs /scratch eclipse-temurin:25-jre df -h /scratch# the longer --mount form says the type out louddocker run -d --name shoplite-db --mount type=volume,source=shoplite-data,target=/var/lib/mysql --env-file db.env -p 3307:3306 mysql:8.4Example 3 · With a named volume, the note survives
Runs in: a terminal with Docker installed
docker run --rm -v notes-data:/data eclipse-temurin:25-jre sh -c 'echo "fees paid on 5 June" > /data/notes.txt'docker run --rm -v notes-data:/data eclipse-temurin:25-jre cat /data/notes.txtdocker ps -a --filter ancestor=eclipse-temurin:25-jrefees paid on 5 June CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
What this code does
- The first run created the volume
notes-data(it did not exist yet), wrote the file into it, and--rmremoved the container. - The second run is a brand-new container, yet it reads the note: the file lives in the volume, not in either container.
docker ps -aconfirms both containers are gone.
A bind mount shows a folder from your own computer inside the container, so both see the same files. A tmpfs mount lives only in memory and is gone when the container stops. With -v, Docker decides by the left side: a plain name means a named volume; a path such as /home/riya/src, ./src or C:\Users\riya\src means a bind mount. Docker creates a named volume the first time you use it.
Two details to remember:
- An empty named volume is first filled with whatever the image has at that path. A bind mount hides the image's files at that path and shows yours instead.
- Relative bind paths such as
./srcwork with-von recent Docker versions (23 and newer); older ones need a full path such as"$PWD"/src.
docker volume ls, inspect and rm
docker volume manages volumes: ls lists them, inspect NAME shows details and rm NAME deletes one with all its data. A volume used by any container, even a stopped one, cannot be removed.
List the volumes, look inside one, and delete one. Docker refuses to remove a volume that a container still uses.
Example 4 · Listing, inspecting and removing volumes
Runs in: a terminal with Docker installed
docker volume lsdocker volume inspect shoplite-datadocker volume rm notes-datadocker volume rm shoplite-dataDRIVER VOLUME NAME
local notes-data
local shoplite-data
[
{
"CreatedAt": "2026-10-16T09:12:44Z",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/shoplite-data/_data",
"Name": "shoplite-data",
"Options": null,
"Scope": "local"
}
]
notes-data
Error response from daemon: remove shoplite-data: volume is in use - [9a1c4e7b2d5f...]What this code does
localis the default driver: the data is stored on the Docker host, at theMountpointpath.notes-datawas unused, so it was deleted with its data.shoplite-datais still used by theshoplite-dbcontainer, so Docker refused and named that container's ID. There is no undo fordocker volume rm.
The Mountpoint in inspect is where the data really sits, such as /var/lib/docker/volumes/shoplite-data/_data. On Linux that is a folder on your disk. On Docker Desktop for Windows and macOS it is inside Docker's small Linux VM, so you cannot browse to it in File Explorer or Finder; use docker run -v or docker cp to reach the files.
Predict the output
Will docker volume rm work?
Pick what Docker does.
Round 1 of 2
No container has ever used notes-data.
docker rm never deletes a named volume. docker rm -v also removes the container's anonymous volumes (volumes with a random ID instead of a name). docker volume prune removes unused anonymous volumes on Docker 23 and newer; add -a to remove unused named ones too, after a careful look.Which one when: named volume for data, bind mount for code
Pick the mount by who owns the data. This small Java program takes its storage folder from DATA_DIR, so a volume can hold it.
Example 5 · VisitCounter: an app that keeps its data in DATA_DIR
import java.io.IOException;import java.nio.file.Files;import java.nio.file.Path;
public class VisitCounter { public static void main(String[] args) throws IOException { String dataDir = System.getenv("DATA_DIR"); boolean throwAway = dataDir == null; Path dir = throwAway ? Files.createTempDirectory("visits") : Path.of(dataDir);
Path file = dir.resolve("visits.txt"); int visits = Files.exists(file) ? Integer.parseInt(Files.readString(file).strip()) : 0; visits++; Files.writeString(file, String.valueOf(visits)); System.out.println("Visit number " + visits + " (stored in " + file.getFileName() + ")");
if (throwAway) { Files.delete(file); Files.delete(dir); System.out.println("No DATA_DIR set: the count was thrown away"); } }}Visit number 1 (stored in visits.txt) No DATA_DIR set: the count was thrown away
What this code does
- The program reads the count from
visits.txt, adds 1 and writes it back. The folder comes from theDATA_DIRenvironment variable, so the storage location is configuration, not code. - Without
DATA_DIRit uses a temporary folder and deletes it, so every run says visit 1: the same thing that happens to a container's own files.
Example 6 · VisitCounter in containers, with and without a volume
Runs in: a terminal with Docker installed, in the folder that holds VisitCounter.java
# three new containers, one volumefor i in 1 2 3; do docker run --rm -e DATA_DIR=/data -v counter-data:/data -v "$PWD":/app -w /app eclipse-temurin:25-jdk java VisitCounter.javadone# a new container that writes to its own layer insteaddocker run --rm -e DATA_DIR=/tmp -v "$PWD":/app -w /app eclipse-temurin:25-jdk java VisitCounter.javaVisit number 1 (stored in visits.txt) Visit number 2 (stored in visits.txt) Visit number 3 (stored in visits.txt) Visit number 1 (stored in visits.txt)
What this code does
- Two mounts at once: a bind mount brings in the program you are editing, a named volume keeps the data. That is the usual split between code and data.
- Every container is new (
--rm), yet the count goes 1, 2, 3 because/datais the volume. WithDATA_DIR=/tmpthe count lives in the container's own layer and starts again at 1.
Use a named volume for data the app owns: MySQL tables, uploaded files, a counter's state. Docker keeps it fast and in the right file format for Linux, and it survives every docker rm. Use a bind mount in development for files you edit: source code, a single-file program, a config file. Use tmpfs for scratch files that must never touch the disk.
Quick picks:
- MySQL data:
-v shoplite-data:/var/lib/mysql. - Program you are editing:
-v "$PWD":/app -w /app. - Temporary files:
--tmpfs /scratch. - Never: a database data folder on a Windows bind mount; it is slow and can fail on file permissions.
Bind mount gotchas: Windows paths and file permissions
A bind mount maps a folder on your computer to a path in the container, with no copy: both sides see the same files, so edits on either side appear on the other.
Bind mounts have two traps: how each terminal writes the current folder, and who owns the files the container creates.
# Git Bash on Windows: stop path rewritingMSYS_NO_PATHCONV=1 docker run --rm -v "$PWD":/app -w /app eclipse-temurin:25-jdk java Hello.java# PowerShelldocker run --rm -v "${PWD}:/app" -w /app eclipse-temurin:25-jdk java Hello.java# Command Promptdocker run --rm -v "%cd%":/app -w /app eclipse-temurin:25-jdk java Hello.java# Linux: create files as your own user, not rootdocker run --rm --user "$(id -u):$(id -g)" -v "$PWD":/app -w /app eclipse-temurin:25-jdk sh -c 'echo ok > out.txt'Each terminal writes "the current folder" differently: $PWD in Git Bash, macOS and Linux, ${PWD} in PowerShell and %cd% in Command Prompt. Git Bash also rewrites arguments that start with / into Windows paths, so -w /app can arrive as C:/Program Files/Git/app; put MSYS_NO_PATHCONV=1 in front of the command to stop that.
On Linux, a container that runs as root creates files on a bind mount that belong to root on your computer, so you cannot edit or delete them later without sudo. Run the container as yourself with --user "$(id -u):$(id -g)". On Docker Desktop, bind mounts from a Windows drive are also slower than named volumes.
Next step
Check your understanding
12 quick questions