CodeBlanks Logo Icon CodeBlanks

Named volumes

Learn to create named volumes with docker volume create.

Named volume

A named volume can be created explicitly or is created automatically on first use. When an empty volume is mounted at a container directory, the contents of that directory in the image are copied into the volume:

docker volume create web-icerik
docker run -d --name web -v web-icerik:/usr/share/nginx/html nginx
# the volume now contains nginx's default index.html

Sharing and anonymous volumes

The same volume can be mounted into several containers; one writes, another reads. If only a container path is given in the form -v /path, an anonymous volume with a random name is created; these are hard to track, so named volumes are preferred:

docker run -d --name yazici -v loglar:/var/log/app api:1.0
docker run --rm -v loglar:/data:ro alpine tail /data/app.log   # :ro read-only
docker run -d -v /data redis       # anonymous volume: 8f3c1a…

Practice A shared volume

Write three commands: create the loglar volume; start a container named api from api:1.0 in the background mounting this volume at /var/log/app; in an alpine container deleted when done, mount the volume read-only at /data and run ls /data.

Starter code

terminal
# buraya yaz

Sample solution

terminal
docker volume create loglar
docker run -d --name api -v loglar:/var/log/app api:1.0
docker run --rm -v loglar:/data:ro alpine ls /data

Expected output

loglar
4d5e6f708192
app.log

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if the volume name given with -v doesn't exist?

  • The container doesn't start
  • Docker creates it automatically Correct answer
  • It errors
  • It is interpreted as a bind mount

Explanation: If the name doesn't start with /, it counts as a named volume.

2 Mount the volume read-only.

Question
docker run --rm -v loglar:/data____ alpine ls /data
Answer
docker run --rm -v loglar:/data:ro alpine ls /data

Explanation: ro. :ro prevents writing.

3 Match.

Term Meaning
docker volume create Creates a volume
-v ad:/yol Named volume
-v /yol Anonymous volume
:ro Read-only

All lessons in Beginner