0
0
DockerHow-ToBeginner · 3 min read

How to Use Named Volume in Docker: Simple Guide

Use a named volume in Docker by creating it with docker volume create [name] and then attaching it to a container with docker run -v [name]:/path/in/container. Named volumes store data persistently outside the container filesystem and can be reused by multiple containers.
📐

Syntax

The basic syntax to use a named volume in Docker is:

  • docker volume create [volume_name]: Creates a named volume.
  • docker run -v [volume_name]:/container/path [image]: Runs a container with the named volume mounted at the specified path inside the container.

This setup keeps data persistent even if the container is removed.

bash
docker volume create mydata

docker run -d -v mydata:/app/data nginx
💻

Example

This example shows how to create a named volume called mydata, run an nginx container using it, and verify the volume exists.

bash
docker volume create mydata

# Run nginx container with the named volume mounted
docker run -d --name webserver -v mydata:/usr/share/nginx/html nginx

# List volumes to verify
docker volume ls

# Inspect the volume details
docker volume inspect mydata
Output
mydata [ { "CreatedAt": "2024-06-01T12:00:00Z", "Driver": "local", "Labels": {}, "Mountpoint": "/var/lib/docker/volumes/mydata/_data", "Name": "mydata", "Options": {}, "Scope": "local" } ]
⚠️

Common Pitfalls

Common mistakes when using named volumes include:

  • Not creating the volume before running the container (Docker will create an anonymous volume instead).
  • Using relative or incorrect paths inside the container.
  • Confusing bind mounts with volumes (bind mounts use host paths, volumes do not).
  • Removing volumes unintentionally when removing containers (named volumes persist unless explicitly removed).
bash
docker run -d -v /mydata:/app/data nginx  # Wrong: this is a bind mount, not a named volume

docker run -d -v mydata:/app/data nginx    # Correct: uses named volume 'mydata'
📊

Quick Reference

CommandDescription
docker volume create myvolumeCreate a named volume called 'myvolume'
docker run -v myvolume:/path/in/container imageRun container with named volume mounted
docker volume lsList all Docker volumes
docker volume inspect myvolumeShow details about the named volume
docker volume rm myvolumeRemove the named volume

Key Takeaways

Create named volumes with 'docker volume create' before using them.
Mount named volumes in containers with '-v volume_name:/container/path'.
Named volumes persist data beyond container life and can be shared.
Avoid confusing named volumes with bind mounts that use host paths.
Use 'docker volume ls' and 'docker volume inspect' to manage volumes.