Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 171 of 8023. Docker Orchestration and StorageFree lesson

Managing Persistent Storage with Docker Volumes

You will learn to define named volumes and bind mounts to ensure data persists across container restarts and lifecycle changes.

In this lesson, you will learn how to use named volumes and bind mounts to ensure your application data survives container deletion and lifecycle changes.

The Problem: Ephemeral Containers

By design, containers are ephemeral. When a container is removed, any data written to its internal filesystem is wiped clean. If your application stores logs, database files, or user uploads inside the container, that data vanishes the moment the container stops or is recreated. Persistent storage allows us to detach the data lifecycle from the container lifecycle.

Named Volumes

Named volumes are the preferred way to persist data in Docker. They are managed entirely by the Docker engine and are stored in a dedicated part of the host filesystem. Because they have a name, they are easy to reference and share across multiple containers.

You define them in your docker-compose.yml file:

services:
  web:
    image: my-app
    volumes:
      - my_data:/app/data

volumes:
  my_data:

Here, /app/data inside the container is mapped to the my_data volume on the host. Even if you remove the container, the data remains inside my_data for the next container to mount.

Bind Mounts

Bind mounts offer a different approach: they map a specific directory on your host machine directly into the container. While named volumes are managed by Docker, bind mounts rely on the host's directory structure. They are incredibly useful for development environments where you want to see your code changes reflected instantly inside a running container:

services:
  web:
    image: my-app
    volumes:
      - ./src:/app/src

In this example, your local ./src folder is "bind-mounted" to /app/src inside the container. Any file you edit on your host machine appears immediately inside the container.

Choosing the Right Tool

Use named volumes when you need to store database state or application data that should be managed by Docker. Use bind mounts when you need direct access to specific host files, such as sharing configuration files or syncing code during development.

Key Takeaway: Named volumes provide managed, portable storage for production data, while bind mounts provide direct host-to-container file sharing for development and configuration workflows.