0
0
DockerHow-ToBeginner · 3 min read

How to Use Volume in Docker: Syntax, Example, and Tips

Use docker volume create to make a volume and docker run -v volume_name:/container/path to attach it to a container. Volumes store data outside the container, so it stays safe even if the container is removed.
📐

Syntax

The basic syntax to create and use a volume in Docker involves two steps:

  • Create a volume: docker volume create volume_name
  • Run a container with the volume: docker run -v volume_name:/path/in/container image_name

Here, volume_name is the name of the volume, and /path/in/container is where the volume will be accessible inside the container.

bash
docker volume create mydata

docker run -d -v mydata:/app/data nginx
Output
mydata <container_id>
💻

Example

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

bash
docker volume create mydata

docker run -d --name webserver -v mydata:/usr/share/nginx/html nginx

docker volume ls

docker inspect webserver
Output
mydata webserver DRIVER VOLUME NAME local mydata [ { "Mounts": [ { "Type": "volume", "Name": "mydata", "Destination": "/usr/share/nginx/html" } ] } ]
⚠️

Common Pitfalls

Common mistakes when using Docker volumes include:

  • Not creating the volume before running the container (Docker can create it automatically, but explicit creation helps avoid confusion).
  • Using relative paths instead of absolute paths inside the container.
  • Confusing bind mounts with volumes (volumes are managed by Docker and safer for data persistence).
  • Forgetting to check volume usage with docker volume ls and docker volume inspect.
bash
docker run -v ./data:/app/data nginx  # Wrong: relative host path without full path

docker run -v /full/path/data:/app/data nginx  # Right: absolute host path

docker volume create mydata

docker run -v mydata:/app/data nginx  # Right: using Docker volume
📊

Quick Reference

Here is a quick cheat sheet for Docker volume commands:

CommandDescription
docker volume create Create a new Docker volume
docker volume lsList all Docker volumes
docker volume inspect Show details about a volume
docker volume rm Remove a Docker volume
docker run -v : Run container with volume attached

Key Takeaways

Create volumes with docker volume create to store data outside containers.
Attach volumes using docker run -v volume_name:/container/path to persist data.
Use absolute paths inside containers and prefer volumes over bind mounts for data safety.
Check volumes with docker volume ls and docker volume inspect.
Remove unused volumes with docker volume rm to free space.