First create a volume sample_vol
docker volume create sample_vol
FROM archlinux/base RUN touch /root/testing [**edited** find note at RUN below] # VOLUME sample_vol:/root [**edited** this will not work, because VOLUME will not accpet named volumes. So this will not mount at /root, it will mount at sample_vol:/root which does not exist] VOLUME "/root" or VOLUME ["/root"] [**edited** this will create a local mount volume only till the time the container is running. I tried to use named volumes like VOLUME ["name:/root"] but didnt work ] # RUN touch /root/testing [**edited** this will not work because volume when mounted will only copy files till it got declared]
build the image
docker build -t archlinux/sample_vol .
checking whether testing file is created in sample_vol
docker run --rm -it -v=sample_vol:/tmp/myvolume archlinux/base ls /tmp/myvolume
It does not show any file testing created
$ docker run --rm -it --name sample_vol archlinux/sample_vol ls /root/testing
It shows the file
testing is created in the
/root/ of build image
sample_vol is not mounted at
testing is created inside it.
Update: Reason i found can be due to
Changing the volume from within the Dockerfile: If any build steps
change the data within the volume after it has been declared, those
changes will be discarded.