Docker Basics (Part 6) : Volumes

In Docker, managing persistent storage is crucial for preserving data across container restarts and ensuring flexibility in data management. Let's explore the differences between mounting local directories and creating volumes, along with practical examples.

Complete Docker Series : View Complete series

Mounting Local Directories vs Creating Volumes

FeatureMounting Local DirectoriesCreating Volumes
Host DependencyDirect access to host files.Abstraction layer; separated from host file system.
Explicit PathSpecify an explicit path on the host.Named volumes; Docker manages details.
Host File OwnershipSubject to host file system ownership.Independent; Docker manages ownership.
Limited IsolationDirect interaction with host file system.Improved isolation from the host.
Named VolumesN/AVolumes can be named for easy reference.
Flexibility and AbstractionLimited flexibility; tied to host specifics.Abstraction layer provides flexibility.
Security ConsiderationsPotential security concerns due to direct access.Better security; reduced direct host interaction.
Volume Plugins SupportN/ASupports plugins for additional features.

Volume Mounting

Command

docker run -v /path/on/host:/path/in/container nginx

Explanation

  • -v /path/on/host:/path/in/container: Mounts the local directory into the container.

  • <host path>:<container path>

Volume mounting provides direct access to host files. However, it comes with limitations in terms of isolation and security, as the container interacts directly with the host file system.

Creating Volumes

Commands

# Create a volume
docker volume create shared-data

# Run containers with the shared volume
docker run -d --name container1 -v shared-data:/app/data1 my-image1
docker run -d --name container2 -v shared-data:/app/data2 my-image2

Explanation

  • docker volume create shared-data: Creates a named volume called shared-data.

  • docker run -d --name container1 -v shared-data:/app/data1 my-image1: Runs a container named container1 with the shared volume for my-image1.

  • docker run -d --name container2 -v shared-data:/app/data2 my-image2: Runs another container named container2 with the same shared volume for my-image2.

Creating volumes introduces an abstraction layer, providing better isolation and security. It allows containers to reference volumes by name, enhancing flexibility and ease of management.

Choose the approach that best suits your requirements, considering factors such as isolation, security, and data management needs. Whether you opt for volume mounting or creating volumes, Docker provides versatile solutions for persistent storage in containerized environments.

Did you find this article valuable?

Support Spotlight by becoming a sponsor. Any amount is appreciated!