Mounting Volumes in Containers
What you'll learn: How to attach Docker volumes to containers at runtime so data persists and can be shared.
The Core Concept
Once you've created a volume, you need to "mount" it into your container — essentially telling Docker to connect that storage location to a specific path inside the container's filesystem. Think of it like plugging an external hard drive into your laptop: the drive exists independently, but you mount it at a specific location (like /media/backup) to access its contents.
Docker provides two main flags for mounting volumes at runtime:
Using -v (Short Syntax)
The -v flag uses a compact syntax: -v volume_name:/container/path
docker run -v mydata:/app/data nginx
This mounts the volume named mydata to /app/data inside the container. Any files written to /app/data are actually stored in the volume, surviving container restarts and deletions.
Using --mount (Verbose Syntax)
The --mount flag is more explicit and readable, using key-value pairs:
docker run --mount type=volume,source=mydata,target=/app/data nginx
Both achieve the same result, but --mount makes it clearer what each parameter represents. It's especially useful when you need additional options like readonly access.
Which to Use?
For beginners, --mount is often clearer. The -v syntax is shorter but can be ambiguous with other mount types you'll learn later.
Key Takeaway: Use -v volume_name:/path or --mount type=volume,source=volume_name,target=/path to connect Docker volumes to containers at runtime, making data persist beyond the container's lifetime.