There are three main use cases for Docker data volumes:
- To keep data around when a container is removed
- To share data between the host filesystem and the Docker container
- To share data with other Docker containers
1 Create a new data volume container
docker create -v /tmp --name datacontainer ubuntu
this created a container named datacontainer based off the ubuntu image and in the directory /tmp
now. if we run a new ubunto contianer with the --volumes-from
docker run -t -i --volumes-from datacontainer ubuntu /bin/bash
echo "I'm not going anywhere" > /tmp/hi
exit
docker run -t -i --volumes-from datacontainer ubuntu /bin/bash
cat /tmp/hi
2 Sharing Data Between the host and docker container
The other command use for docker container is as a means of sharing files between the host machine and the docker container. This works differently from the last example. There's no need to create a "data-only" container first. you can simple run as container of any docker image and override one of is directories with the contents of a directory on the host system.
mkdir ~/nginxlogs
docker run -d -v ~/nginxlogs:/var/log/nginx -p 5000:80 -i nginx
3 Create an independent volume
docker volume create --name Datavolume1
docker run -ti --rm -v Datavolume1:/datavolume1 ubuntu
echo "Example1" > /datavolume1/Example1.txt
docker volume inspect DataVolume1
docker run --rm -ti -v DataVolume1:/datavolume1 ubuntu
cat /datavolume1/Example1.txt
4 Create volume that presiss when the container is Remove
we'll create a volums at the same time as the container
Delete the container
then attach the volume to new container
docker run -ti --name=Container2 -v DataVolume2:/datavolume2 ubuntu
The -v flag
if the first argument begins with / or ~/ you will create bindmount
no / or ~/ will name the volume
- -v /path:/path/in/container is mounts the hosts directory
- -v path:/path/in/container create volume name path with no relationship to the host