Understanding docker -v command

Tenali_raman picture Tenali_raman · Aug 28, 2015 · Viewed 23.3k times · Source

I was just going through this tutorial on Youtube, trying to understand the use of the -v command.

Why is the author using the -v command? He uses the command, like so:

docker run -v /var/lib/mysql --name=my_datastore -d busybox echo "my datastore"

Now I understand the above command to an extent:

  • --name=my_datastore gives the container a specific name.
  • -d busybox starts a container in detached mode, based on the busybox image.

After the command is executed the below line is echoed to the console.

my datastore 

Now, the part I don't understand is the following:

-v /var/lib/mysql

Why is the -v command used here, and why the path /var/lib/mysql specified?

I am having difficulty understanding why the above line is used and in what context. Can anybody explain?

Answer

larsks picture larsks · Aug 28, 2015

The -v (or --volume) argument to docker run is for creating storage space inside a container that is separate from the rest of the container filesystem. There are two forms of the command.

When given a single argument, like -v /var/lib/mysql, this allocates space from Docker and mounts it at the given location. This is primarily a way of allocating storage from Docker that is distinct from your service container. For example, you may want to run a newer version of a database application, which involves tearing down your existing MySQL container and starting a new one. You want your data to survive this process, so you store it in a volume that can be accessed by tour database container.

When given two arguments (host_path:container_path), like -v /data/mysql:/var/lib/mysql, this mounts the specified directory on the host inside the container at the specified path (and, to be accurate, this can also be used to expose host files inside the container; for example -v /etc/localtime:/etc/localtime would make /etc/localtime on the host available as /etc/localtime inside the container). This is a way of either feeding information into your container, or providing a way for your container to make files accessible to the host.

If a container has volumes available, either through the use of the -v command line argument or via the VOLUME directive in a Dockerfile, these volumes can be accessed from another container using the --volumes-from option:

docker run --volumes-from my_datastore ...

This will make any volumes defined in the source container available in the container you're starting with --volumes-from.

This is discussed in more detail in the Docker Volumes documentation.