Docker Assign a volume to a container


A Docker volume is a file or directory which persists beyond the lifetime of the container. It is possible to mount a host file or directory into a container as a volume (bypassing the UnionFS).

Add a volume with the -v command line option:

docker run -d -v "/data" awesome/app

This will create a volume and mount it to the path /data inside the container.

  • Note: You can use the flag --rm to automatically remove the volume when the container is removed.

Mounting host directories

To mount a host file or directory into a container:

docker run -d -v "/home/foo/data:/data" awesome/app
  • When specifying a host directory, an absolute path must be supplied.

This will mount the host directory /home/foo/data onto /data inside the container. This "bind-mounted host directory" volume is the same thing as a Linux mount --bind and therefore temporarily mounts the host directory over the specified container path for the duration of the container's lifetime. Changes in the volume from either the host or the container are reflected immediately in the other, because they are the same destination on disk.

UNIX example mounting a relative folder

docker run -d -v $(pwd)/data:/data awesome/app

Naming volumes

A volume can be named by supplying a string instead of a host directory path, docker will create a volume using that name.

docker run -d -v "my-volume:/data" awesome/app

After creating a named volume, the volume can then be shared with other containers using that name.