Docker Volumes: Persistent Data for Ephemeral Containers
Think of a Docker Volume as an external hard drive for your container. It persists data even after a container is removed, perfect for databases or user uploads. The footgun is confusing volumes with bind mounts, which are less portable.
WHY IT EXISTS: Containers are designed to be ephemeral. When a container is stopped and removed, any data written inside its filesystem is lost forever. This is a problem for stateful applications like databases that need to persist data across container restarts and updates.
THE MENTAL MODEL: A Docker Volume is an external hard drive for your container. You can attach it to a running container to read and write data. When you destroy the container, the "hard drive" (the volume) remains untouched, with all its data intact, ready to be attached to a new container.
HOW IT WORKS: Docker manages a dedicated storage area on the host machine, completely separate from the container's layered filesystem. When you mount a volume into a container (e.g., -v my-data:/path/in/container), Docker makes the data from the volume available at that path. Any I/O operations the container performs on that path are redirected to the volume on the host, ensuring persistence. Volumes are created and managed via the Docker CLI (e.g., docker volume create my-volume).
WHEN TO USE IT: Use volumes for any data that needs to outlive a single container instance. This is essential for database storage (like PostgreSQL or MySQL data directories), storing user-generated content like file uploads, and sharing data between multiple containers.
WHEN NOT TO USE IT: Don't use volumes for your application's source code; that should be baked into the image during the build process. For local development where you need to mount your source code directly into a container for live editing, a bind mount is more appropriate, but volumes are preferred for production workloads due to their portability.
ONE CANONICAL EXAMPLE: To run a PostgreSQL database and ensure its data persists, you mount a named volume. docker run -d --name db -v pgdata:/var/lib/postgresql/data postgres Here, pgdata is the named volume. All database files created by PostgreSQL inside the container at /var/lib/postgresql/data are saved to this volume. You can remove the db container, run a new one with the same volume mount, and your database will be exactly as you left it.
Read the original → docs.docker.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.