In this lesson, you will learn why containers are intentionally "forgetful" and how volumes allow you to keep your data safe even after a container is destroyed.
The Problem: Ephemeral Writable Layers
As we discussed in our lessons on the Union File System and Copy-on-Write (CoW) strategies, every container has a thin, writable layer on top of its immutable image. While this layer is perfect for temporary changes during the container's runtime, it has a major drawback: it is ephemeral.
When a container is deleted, that writable layer—and everything inside it—vanishes forever. If your application stores user uploads, database records, or configuration files within the container's standard filesystem, those files are lost the moment the container stops.
The Solution: Persistent Volumes
To achieve data integrity, we move data outside the container’s lifecycle using Volumes. A volume is essentially a directory on your host machine (or a remote storage provider) that is "mounted" into the container.
Think of it like a USB drive: the container can read and write to the USB drive as if it were part of its own internal storage, but when you unplug the drive (stop/delete the container), your data remains perfectly safe on the hardware.
Here is how it looks in practice:
# Mounting a host directory into a container
docker run -v /my/host/data:/app/data my-application
In this command, /my/host/data is the persistent storage on your machine, and /app/data is the path inside the container. Anything written to /app/data is actually written directly to your host's disk.
Why Use Volumes?
- Decoupling: Your data lives independently of the container lifecycle. You can destroy and recreate a container without touching the data files.
- Persistence: Data survives container crashes, updates, and restarts.
- Performance: By bypassing the storage driver overhead of the Union File System, volumes can sometimes offer faster disk I/O, which is vital for database-heavy applications.
Key Takeaway: While a container's writable layer is temporary and bound to the container's lifecycle, volumes provide a mechanism to decouple your data from the container, ensuring it remains intact even after the container is deleted.