G
GuideDevOps
Lesson 6 of 13

Volumes & Bind Mounts

Part of the Docker tutorial series.

By default, data in a container is ephemeral. If the container is deleted, the data is gone. To persist data (like databases or logs), Docker provides two main methods: Volumes and Bind Mounts.

1. Named Volumes (Recommended)

Volumes are stored in a part of the host filesystem which is managed by Docker (/var/lib/docker/volumes/). This is the best way to persist data in Docker.

Create and Use a Volume

Action:

# Create a named volume
docker volume create my-db-data
 
# Run a container using that volume
docker run -d --name my-db -v my-db-data:/var/lib/mysql mysql:8

Result:

my-db-data
605c77e624dd1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1v2w3x4y5z

Inspect the Volume

Action:

docker volume ls

Result:

DRIVER    VOLUME NAME
local     my-db-data

2. Bind Mounts

Bind mounts map a specific path on your host machine to a path in the container. This is excellent for development (e.g., live-syncing source code).

Action:

# Map current local directory to /app inside the container
docker run -d --name dev-server -v $(pwd):/app nginx

Result: (Any change you make locally to files in $(pwd) will be instantly reflected inside the container)


3. Comparison

FeatureNamed VolumeBind Mount
Storage LocationManaged by DockerAnywhere on host
PortabilityHigh (Works across OS)Low (Host-specific paths)
PerformanceExcellentVaries (Can be slow on Mac/Win)
Best Use CaseDatabases, ProductionLocal code development

Summary

  • No Volume: Data is lost when container is removed.
  • Named Volume: Docker handles where data is stored.
  • Bind Mount: You tell Docker exactly where on your disk to store data.