Containers Are Cattle, Data Is Not

The Writable Layer Trap

Scenario: The notes app has run happily for months, saving files inside the container. Tonight's routine redeploy recreates the container… and every user's data is gone. No bug, no attack - just a fundamental misunderstanding of where the data lived.

Recall from the layers module that an image is a stack of read-only layers. When a container runs, Docker adds one more layer on top that it can write to - the writable layer. Every file the app creates or edits while running lands there. The catch: that layer is deleted the instant the container is removed. This is a feature, not a bug - it's what lets containers stay disposable, identical, and replaceable (an idea often summarized as "cattle, not pets": don't nurse one broken container back to health, just delete it and start a fresh one). But it has one big consequence: anything you actually want to keep must live outside the container, in a separate location Docker won't delete along with it - a volume.

┌──────────────┐   ┌──────────────┐
│ container v1 │   │ container v2 │   ← created & destroyed freely
└──────┬───────┘   └──────┬───────┘
       │    mounted at /data    │
       ▼                        ▼
  ┌────────────────────────────────┐
  │     volume: notes-data         │   ← survives forever
  └────────────────────────────────┘
$ docker volume create notes-data
$ docker run -d --name notes -v notes-data:/data notes-app:v2
$ docker volume ls
$ docker inspect notes    # "Mounts" section shows what's mounted where
Note: Deleting a container does not delete its named volumes. That's the point - but also remember docker volume prune exists when cleaning up.