Docker is designed to promote Stateless applications.
The idea is that a container should be something disposable.
That is, you should be able to delete your container at any time, launch it again, and everything continues to work the same.
This is one of the most important concepts in Docker (perhaps the most important). To understand it, we need to look again at how a container is built internally 👇.
Remembering the Layers
When we saw the chapter on Images, we said that a Docker image is a set of read-only layers stacked on top of each other.
Images are immutable. Once created, they cannot be changed.
This is what allows them to be reusable between one instance and another. And what makes it such an efficient system.
But a system, an application, almost always needs to “do things.” That is, touch files, create things…
If the image is read-only… how is it possible to write files inside a container?
The Container Layer (Read-Write Layer)
When you run docker run, Docker takes the image layers and adds a thin extra layer on top.
This is the Container Layer and it is the only layer that is readable and writable.
Any changes you make in the container (creating a file, modifying a configuration, saving a log in the DB) are written exclusively to this top layer.
The original image (the layers below) is never touched. It remains pristine.
The Lifecycle of Data
The writable layer is tied to the lifecycle of the container.
Let’s look at the three states:
Running Container (Up): You can write data. It is saved in the R/W layer.
Stopped Container (Exited): You do a docker stop. The container shuts down, but the writable layer is still there. If you do docker start again, your data will still be there.
Important! Stopping a container does NOT delete the data.
Deleted Container (Removed): You do a docker rm. This is where the tragedy happens. When the container is destroyed, Docker also destroys its writable layer.
So when you delete a container, everything you had written in that layer is instantly erased (the new database, logs, uploaded files).
The Problem: We Need Persistence
Containers being immutable is very interesting. A nice theory, and part of the basic functioning of the system.
But as you may have started to wonder, in the real world, we need to save things:
- A database needs to remember the clients.
- A web server needs to save the images users upload.
If we can’t save the data inside the container because it disappears with it… where do we save it?
We need a mechanism to “take” that data out of the container and save it on our computer (the Host), so that it survives even if the container goes down.
Docker offers us two main solutions for this:
- Volumes: The Docker-managed option.
- Bind Mounts: Mapping folders from your PC (ideal for development).
In the next article, we will look at the recommended solution for databases: Volumes.
