In previous episodes, we explored Docker Compose, Networking, and Swarm. Now it’s time to tackle one of the most important aspects of containerized applications: data persistence.
🔹 Why Persistent Storage Matters
By default, Docker containers are ephemeral:
- Any data stored inside a container is lost when the container is removed.
- To preserve data across container restarts or upgrades, we need volumes or bind mounts.
🔹 Types of Docker Storage
- Volumes
- Managed by Docker
- Stored in
/var/lib/docker/volumes/
on the host - Can be shared between containers
- Ideal for databases and persistent app data
- Bind Mounts
- Use a directory from the host machine
- Provides full control over files
- Useful for development environments
- Tmpfs Mounts
- Stored in memory only
- Great for caching or temporary data
🔹 Creating and Using Volumes
# Create a volume
docker volume create my_data
# Run a container using the volume
docker run -d -v my_data:/app/data my_app
-
my_data
persists even ifmy_app
is removed.
🔹 Bind Mount Example
docker run -d -v /host/path:/container/path my_app
- Changes on the host path are immediately reflected inside the container.
🔹 Using Volumes in Docker Compose
version: '3'
services:
db:
image: postgres:latest
volumes:
- db_data:/var/lib/postgresql/data
volumes:
db_data:
- Data survives container restarts and
docker-compose down
.
🔹 Best Practices
- Use named volumes for production data.
- Backup volumes regularly.
- Avoid storing sensitive credentials in volumes directly; use secrets instead.
- Use read-only mounts where appropriate for security.
🔹 Hands-On Challenge
- Create a PostgreSQL container with a named volume.
- Insert some data.
- Stop and remove the container.
- Run a new container attached to the same volume and verify the data persists.
✅ Next Episode: Episode 20 — Docker Security Best Practices & Secrets Management
Top comments (0)