How to Persist Data in Docker: Volumes and Bind Mounts Explained
To persist data in Docker, use
volumes or bind mounts which store data outside the container's writable layer. This keeps your data safe even if the container is deleted or recreated. Use docker run -v or docker volume create commands to set this up.Syntax
Docker provides two main ways to persist data: volumes and bind mounts.
-v volume_name:/container/path: Mounts a Docker volume inside the container.-v /host/path:/container/path: Mounts a host directory inside the container (bind mount).
Volumes are managed by Docker and stored in Docker's storage area. Bind mounts use existing directories on your host machine.
bash
docker run -v volume_name:/container/path image_name docker run -v /host/path:/container/path image_name
Example
This example creates a Docker volume named mydata and runs a container that writes a file inside it. The data persists even after the container stops or is removed.
bash
docker volume create mydata
docker run --rm -v mydata:/data busybox sh -c "echo 'Hello Docker' > /data/greeting.txt"
docker run --rm -v mydata:/data busybox cat /data/greeting.txtOutput
Hello Docker
Common Pitfalls
Common mistakes when persisting data in Docker include:
- Using container writable layer only, which loses data when container is removed.
- Incorrect volume or bind mount paths causing data not to persist.
- Permissions issues on bind mounts preventing container access.
Always verify paths and permissions. Use volumes for easier management and portability.
bash
docker run -v /wrong/host/path:/data image_name # Wrong path, data won't persist
docker run -v mydata:/data image_name # Correct volume usageQuick Reference
| Command | Description |
|---|---|
| docker volume create myvolume | Create a new Docker volume named myvolume |
| docker run -v myvolume:/app/data image | Mount volume inside container at /app/data |
| docker run -v /host/path:/app/data image | Bind mount host directory into container |
| docker volume ls | List all Docker volumes |
| docker volume rm myvolume | Remove a Docker volume |
Key Takeaways
Use Docker volumes or bind mounts to keep data safe beyond container life.
Volumes are managed by Docker and are easier to use and share.
Bind mounts link host directories but need careful permission handling.
Always specify correct paths and check permissions to avoid data loss.
Data in container writable layer is lost when container is removed.