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.

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

  1. 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
  1. Bind Mounts
  • Use a directory from the host machine
  • Provides full control over files
  • Useful for development environments
  1. 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 if my_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

  1. Create a PostgreSQL container with a named volume.
  2. Insert some data.
  3. Stop and remove the container.
  4. Run a new container attached to the same volume and verify the data persists.

✅ Next Episode: Episode 20 — Docker Security Best Practices & Secrets Management


Source: DEV Community.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.