Docker Data Persistence: Volumes, Bind Mounts, and tmpfs

·1394 words

Removing a container also removes its writable layer, which stores file changes made while the container runs. A new container cannot access database files stored only in that layer. This guide explains how to retain data with a volume, access host files through a bind mount, and use tmpfs for temporary storage in memory.

Common commands at a glance
#

Removing a volume deletes its data. Use the removal command below only for the test volume created in this guide.

CommandWhat it does
docker volume create --label docker-learning.exercise=volumes "$volume_name"Create a volume for this exercise after setting its name below
docker volume lsList local volumes
docker run --mountConfigure a volume, bind mount, or tmpfs for a container
docker volume inspect "$volume_name"Inspect the exercise volume and its labels
docker volume rm "$volume_name"Verify the name and label, then delete the exercise volume and its data

Where Does Container Data Actually Live?
#

Each container has a writable layer where files created or modified at runtime are written. When the container is deleted, this layer is also deleted, and data disappears with it.

If data needs to persist after container deletion or be shared among multiple containers, use other storage methods.

flowchart TD
    accTitle: What happens to data when a container is removed
    accDescr: Files written outside mounts go to the container writable layer and are removed with the container. After mounting a named volume, files written to that mount path go into the separate volume. Removing the container leaves the volume, which a new container can mount to read the data.
    image["Image read-only layers"] --> old["Container A"]
    old --> layer["Changes outside mounts\ncontainer writable layer"]
    old -->|Mount at /data, then write| volume["Named Volume\nindependent of container"]
    layer -->|Remove container A| removed["Writable layer removed"]
    old -->|Remove| gone["Container A removed"]
    volume -->|Mount same volume| replacement["Container B reads old data at /data"]

A volume does not automatically receive every file in a container. Only content written to the mount point (such as /data) goes into the volume; files elsewhere remain in the container writable layer.

Four Storage Methods—How to Choose?
#

TypeData OwnershipLifecycleTypical UseNotes
Container writable layerInside containerDeleted with containerTemporary computation, cacheData lost when container deleted
Named VolumeDocker-managedIndependent of containerDatabase files, application dataDeleting volume deletes data; not a backup
Bind MountHost pathIndependent of containerConfig files, development codeContainer can modify host files; watch permissions
tmpfsMemoryGone when container stopsTemporary files, high-speed cacheNot persistent; data lost when container stops

For daily development and production deployment, mainly use Named Volume and Bind Mount; tmpfs suits special temporary data scenarios.

Preserve Data with Named Volume
#

Docker reuses an existing volume with the same name. Use mktemp to generate a random suffix, then add a label to identify the exercise volume. Run the rest of the exercise in the same shell so volume_name stays set.

Shell
volume_name_dir=$(mktemp -d "${TMPDIR:-/tmp}/notes-data.XXXXXXXX") &&
  volume_name=${volume_name_dir##*/} &&
  rmdir "$volume_name_dir" &&
  docker volume create --label docker-learning.exercise=volumes "$volume_name"

Once creation succeeds, docker volume ls lists the new volume. Before writing to it, use docker volume inspect to check that Name matches the name you generated and Labels contains docker-learning.exercise with the value volumes.

Shell
docker volume ls
docker volume inspect "$volume_name"

Start a temporary container and write a file to the volume:

Shell
docker run --rm --mount "type=volume,src=$volume_name,dst=/data" \
  busybox:1.37 sh -c 'printf "saved data\n" > /data/note.txt'

--mount makes the exercise volume available at /data inside the container. The container is removed after running (--rm), and the volume retains the data.

Start another container and read the same volume:

Shell
docker run --rm --mount "type=volume,src=$volume_name,dst=/data" \
  busybox:1.37 cat /data/note.txt

Reading saved data proves the data persisted.

The Mountpoint field from docker volume inspect shows where Docker Engine stores the data. Mount the volume in a container to access its files and avoid editing Docker’s internal storage directly.

Share Host Files with Bind Mount
#

Create a separate directory for the exercise. Keep using the same shell so shared_dir stays set. With a remote Docker Engine, the bind mount path has to exist on the Engine host.

Shell
shared_dir=$(mktemp -d "$PWD/docker-bind-demo.XXXXXX")
printf 'host file\n' > "$shared_dir/note.txt"

Mount this directory to a container:

Shell
docker run --rm --mount type=bind,src="$shared_dir",dst=/data,readonly \
  busybox:1.37 cat /data/note.txt

The container can read the host file. readonly makes the mount read-only; the container cannot modify it.

Remove readonly to allow container writes:

Shell
docker run --rm --mount type=bind,src="$shared_dir",dst=/data \
  busybox:1.37 sh -c 'printf "from container\n" >> /data/note.txt'

cat "$shared_dir/note.txt"

Content written by the container appears directly in the host file.

Bind mount risk: Processes inside the container can modify host files. If the container is compromised or the application has bugs, host data may be damaged. In production, use cautiously; prefer read-only mounts or limit mount path scope.

Clean up:

Shell
rm -- "$shared_dir/note.txt"
rmdir -- "$shared_dir"

When Is tmpfs Appropriate?
#

tmpfs mounts put data in memory; data disappears when the container stops. They are not a secrets-management mechanism or a guarantee that data never reaches persistent storage: on Linux, swap may write memory pages to disk. Suitable for:

  • High-speed cache not requiring persistence
  • Large amounts of small temporary files for computation
Shell
docker run --rm --mount type=tmpfs,dst=/tmp \
  busybox:1.37 sh -c 'printf "temp data\n" > /tmp/file.txt && cat /tmp/file.txt'

The container can read and write /tmp while running, but data is not retained after stopping.

tmpfs is provided by the Linux Engine. Docker Desktop uses a Linux Engine inside a virtual machine for Linux containers. tmpfs data also consumes memory available to the container; if the Engine host uses swap, memory pages can be written to disk. Do not use tmpfs alone to protect keys or tokens; use a secrets-management mechanism appropriate to the deployment.

Mount Command Syntax and Common Pitfalls
#

Docker provides two mount parameter forms: --mount and -v / --volume.

Recommend –mount for clearer parameters:

Shell
docker run --mount type=volume,src=my-vol,dst=/data ...
docker run --mount type=bind,src=/host/path,dst=/data,readonly ...
docker run --mount type=tmpfs,dst=/tmp ...

-v also works, more concise format but easier to confuse:

Shell
docker run -v my-vol:/data ...              # named volume
docker run -v /host/path:/data:ro ...       # bind mount
docker run -v /host/path:/data ...          # bind mount (read-write)

-v usually auto-creates the directory when bind source doesn’t exist; --mount type=bind defaults to requiring source to exist. To avoid accidental mounts, confirm the path exists first.

The form -v /data, with only a container destination, creates an anonymous volume rather than a bind mount. Anonymous volumes may remain after a container is removed, so do not treat them as temporary directories.

Command aliases:

  • docker volume ls = docker volume list
  • docker volume rm = docker volume remove
  • -v and --volume are different notations for the same parameter, not aliases of --mount

Common pitfalls:

  • A mount hides files at the target path. With an empty volume, Docker copies any files already at that path into the volume by default. Use volume-nocopy to skip the copy. A bind mount hides the original files without copying them.
  • Bind mount source doesn’t exist. --mount type=bind defaults to requiring source path to exist; missing source causes errors. -v may auto-create, but may not be what you want.
  • Permission and UID/GID mismatch. Container user and host user UIDs may differ, causing read/write failures.
  • Path mistake. Bind mounts require absolute paths. Relative paths behave inconsistently across different working directories.

Cleanup and Backup Boundaries
#

Use docker volume inspect "$volume_name" to check the name and the docker-learning.exercise=volumes label again. Delete the volume only after confirming that it belongs to this exercise and you no longer need its contents.

Shell
docker volume rm "$volume_name"

Important: Deleting a volume permanently deletes data. Named volumes don’t automatically become backups and don’t automatically copy to another host. If backups are needed, separately use docker run to mount the volume to a temporary container and copy data with tar or rsync.

docker volume prune removes volumes not used by containers. By default, it removes only anonymous volumes; --all also removes unused named volumes. Read the help for your Docker version and confirm the data is disposable before running it. This exercise removes only one labeled volume and does not run prune.

References
#