Skip to content

Data & Volumes

A container has a writable layer on top of its read-only image layers. Every file you create, modify, or delete inside a running container lives only in that writable layer. The moment the container is removed with docker rm, that layer is gone — permanently.

This is by design. Containers are meant to be stateless, disposable, and reproducible. You should be able to stop a container, throw it away, and start a fresh one from the same image at any time. If your data lived inside the container, that model breaks down.

Image layer (read-only) ← node:22-alpine base
Image layer (read-only) ← COPY app files
Writable layer (container) ← runtime writes (gone on docker rm)

Docker gives you three mechanisms to break out of the ephemeral writable layer:

OptionWhere data livesManaged by
Named volumesDocker-managed directory on the hostDocker
Bind mountsAny path on the host filesystemYou
tmpfs mountsHost RAM only (never written to disk)Kernel

Each option has different trade-offs around portability, performance, and use case. This module walks through them one by one.

Before learning how to persist data, it is worth seeing the problem first-hand. The snippet below creates a file inside a container, removes the container, and runs a fresh one — the file is gone.

# Run a container and write a file
docker run --name ephemeral-demo alpine sh -c "echo 'hello world' > /data/message.txt && cat /data/message.txt"

# Remove the container
docker rm ephemeral-demo

# Start a brand-new container from the same image
docker run --rm alpine sh -c "cat /data/message.txt 2>/dev/null || echo 'File is gone!'"
LessonTopic
Named Volumesdocker volume create/ls/inspect/rm, mounting volumes, Docker-managed storage
Bind MountsMapping host paths into containers, live-editing source code
Volumes vs Bind MountsComparison table, portability, performance, read-only mounts
Backup & RestoreArchiving volumes with a throwaway container, restoring, migrating
What happens to files written inside a container when you run `docker rm`?
Which storage option is managed entirely by Docker and stored in a Docker-controlled directory?
A tmpfs mount stores data in which location?