LESSON · 1 OF 6

Why container data disappears

Why container data disappears

Here is a fact that catches everyone out once: when you remove a container, everything written inside it is gone. A database container you docker rm takes its data with it. Understanding why leads straight to the fix.

The writable layer is tied to the container

Recall that a container is a read-only image plus a thin writable layer on top. Every file the container creates or changes at run time - log files, uploaded images, database rows - lives in that writable layer.

That layer belongs to the container. Stop the container and the layer survives, so a docker start brings the data back. But docker rm deletes the container and its writable layer together. The data is destroyed with it, permanently.

Why this is by design, not a flaw

Containers are meant to be disposable. You should be able to kill one and start a fresh copy without a second thought - that is what makes them easy to scale and replace. Data that mattered would make them fragile. So Docker keeps the container's own storage throwaway on purpose, and gives you a separate mechanism for data you want to keep.

The fix: store data outside the container

Anything that must outlive the container goes outside the writable layer, onto storage the container only borrows. Docker offers two ways to do this:

  • bind mounts - map a folder on the host into the container.
  • named volumes - storage Docker manages for you, kept separate from any one container.

Both make a location inside the container point at storage that lives independently, so removing the container leaves the data untouched. The next two nodes cover each in turn. The rule to remember: never keep data you care about in a container's writable layer.

Spin up a fresh environment and practice live.
docker · fresh machine · ready in under a minute