docker volume rm docker-volume-example -f
docker volume create docker-volume-example
docker run --rm -v docker-volume-example:/path/inside/container -it ubuntu bash -c 'echo $(date) > /path/inside/container/newly_created_data._dat'
Because of the --rm flag, the container is completely gone. Because of the volume mount, we are able to persist data outside of the container and across multiple container creations.
cat /var/lib/docker/volumes/docker-volume-example/_data/newly_created_data._dat
You'll notice that after we have ran our work task in the container, only the data is left. Future uses of this volume will use a brand new container but have access to the previous data.
The -v docker-volume-example:/path/inside/container
is like mounting a new physical volume to a path.
docker run --rm -v $PWD:/hostfs -it ubuntu bash
ls -lahrt /hostfs
careful, you have given the container access to $PWD. Some contianers start as root, others dont. Linux file permissions are passed from the HOST to the CONTAINER. Type exit
or CTRL+d
One other thing to note is that there is a default docker behavior that only applies to volumes managed via "docker volume" commands. It does NOT apply to direct path mounts.
When you mount a new(empty) docker volume to a path inside a container, docker will copy the contents of the destination path from the docker image, into the new volume. An example of this behavior can be seen below.
docker volume rm docker-volume-example -f
docker volume create docker-volume-example
run an nginx container(no -it
) that immediately exits, docker copies the contents of the mount path into the volume
docker run --rm -v docker-volume-example:/usr/share/nginx nginx bash
ls -lahrt /var/lib/docker/volumes/docker-volume-example/_data/
mkdir /tmp/nginx
run same docker command with a direct path instead of docker volume to show that the data is NOT copied over
docker run --rm -v /tmp/nginx:/usr/share/nginx nginx bash
ls -lahrt /tmp/nginx/
rm -r /tmp/nginx