The container layer is temporary
Why data disappears and where to keep it.
Everything a program writes to the container's file system ends up in its top writable layer. This layer lives as long as the container exists: it survives docker stop and docker start but disappears with docker rm. And containers are removed all the time: when an image is updated, the old container is replaced with a new one. If a database kept its files inside the container, it will be empty after the update.
That is why containers separate the program from the data. The program comes from the image and can be replaced at any moment. The data lives outside, in a volume or a host folder, and is mounted into the new container at the same place. The container becomes replaceable and the data permanent.
docker run -d --name db -e POSTGRES_PASSWORD=example -v pgdata:/var/lib/postgresql/data postgres:16.4
docker rm -f db
docker run -d --name db -e POSTGRES_PASSWORD=example -v pgdata:/var/lib/postgresql/data postgres:16.4
The container was removed and created again, but the pgdata volume stayed, and the database sees its previous data.
The writable layer is also slower than an ordinary disk: it works through a storage driver with copy-on-write. For databases, user uploads and caches that write to disk heavily, a volume is faster. It makes sense to keep only temporary files in the container layer, files you do not mind losing.
A common mistake is to check that data survives docker restart and decide everything is fine. A restart does not remove the layer, so the check proves nothing. The real check is to remove the container and create a new one with the same volumes.
Practice
When the data disappears
A database writes its files to the container layer without volumes. After which operation will the files disappear?
- docker stop
- docker restart
- docker rm
- docker logs
What belongs in a volume
What should be kept in a volume rather than in the container layer? Mark all.
- Database files
- Files uploaded by users
- Application code from the image
- Temporary files for a single request
An honest check
Which Docker command removes a container so you can check that the data survives its replacement? Write the command without the container name.