0
0
DockerConceptBeginner · 3 min read

What Is Volume in Docker: Simple Explanation and Usage

A volume in Docker is a special storage area outside the container's writable layer that lets you save and share data persistently. Volumes keep data safe even if the container is deleted or recreated, making them ideal for databases or files that need to survive container restarts.
⚙️

How It Works

Think of a Docker container like a temporary workspace that disappears when you close it. A volume is like a separate, permanent filing cabinet where you can store important papers. Even if you throw away the workspace, the filing cabinet stays intact.

Technically, a volume is a folder stored on your computer or server outside the container. Docker connects this folder to the container, so the container can read and write files there. This way, data is not lost when the container stops or is removed.

Volumes also let multiple containers share the same data safely, like coworkers accessing the same filing cabinet without losing anything.

💻

Example

This example shows how to create a volume and use it with a container to save data persistently.

bash
docker volume create mydata

docker run -d --name mycontainer -v mydata:/app/data busybox sh -c "echo 'Hello Docker' > /app/data/greeting.txt && sleep 3600"

docker run --rm -v mydata:/app/data busybox cat /app/data/greeting.txt
Output
Hello Docker
🎯

When to Use

Use Docker volumes when you need to keep data safe beyond the life of a container. For example:

  • Storing database files so data is not lost when the database container restarts.
  • Saving user uploads or logs that must persist.
  • Sharing configuration files or data between multiple containers.

Volumes are better than storing data inside containers because container storage is temporary and deleted with the container.

Key Points

  • Volumes store data outside the container's writable layer.
  • They keep data safe even if containers are removed.
  • Volumes can be shared between multiple containers.
  • They are managed by Docker and easy to back up or migrate.

Key Takeaways

Docker volumes provide persistent storage independent of container life cycles.
Use volumes to save important data like databases, logs, or user files.
Volumes can be shared safely between multiple containers.
They are managed by Docker and stored outside container layers.
Volumes help keep data safe when containers are deleted or recreated.