Skip to content

Instantly share code, notes, and snippets.

@xandout
Last active April 1, 2020 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save xandout/e85a071b912fda6aa654d5d1e6fe0722 to your computer and use it in GitHub Desktop.
Save xandout/e85a071b912fda6aa654d5d1e6fe0722 to your computer and use it in GitHub Desktop.
Docker volume notes for a friend

cleanup

docker volume rm docker-volume-example -f

create a new volume to be managed by docker.

on your HOST_FS at /var/lib/docker/volumes/docker-volume-example/_data/

docker volume create docker-volume-example

Run an ubuntu container with the volume we made. Create new data inside volume

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.

You can also mount paths directly from the host to the container like this

docker run --rm -v $PWD:/hostfs -it ubuntu bash

from here, run

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.

cleanup

docker volume rm docker-volume-example -f

create volume

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

show the html folder on your HOST_FS

ls -lahrt /var/lib/docker/volumes/docker-volume-example/_data/

make a temp path to use

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

nothing there

ls -lahrt /tmp/nginx/

rm -r /tmp/nginx

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment