Docker Anonymous Volumes

Raphael Rafatpanah picture Raphael Rafatpanah · Jul 7, 2017 · Viewed 8.4k times · Source

I've seen Docker volume definitions in docker-compose.yml files like so:

-v /path/on/host/modules:/var/www/html/modules

I noticed that Drupal's official image, their docker-compose.yml file is using anonymous volumes.

Notice the comments:

volumes:
  - /var/www/html/modules
  - /var/www/html/profiles
  - /var/www/html/themes
  # this takes advantage of the feature in Docker that a new anonymous
  # volume (which is what we're creating here) will be initialized with the
  # existing content of the image at the same location
  - /var/www/html/sites

Is there a way to associate an anonymous volume with a path on the host machine after the container is running? If not, what is the point of having anonymous volumes?

Full docker-compose.yml example:

version: '3.1'

services:

  drupal:
    image: drupal:8.2-apache
    ports:
      - 8080:80
    volumes:
      - /var/www/html/modules
      - /var/www/html/profiles
      - /var/www/html/themes
      # this takes advantage of the feature in Docker that a new anonymous
      # volume (which is what we're creating here) will be initialized with the
      # existing content of the image at the same location
      - /var/www/html/sites
    restart: always

  postgres:
    image: postgres:9.6
    environment:
      POSTGRES_PASSWORD: example
    restart: always

Answer

BitMask777 picture BitMask777 · May 11, 2018

Adding a bit more info in response to a follow-up question/comment from @JeffRSon asking how anonymous volumes add flexibility, and also to answer this question from the OP:

Is there a way to associate an anonymous volume with a path on the host machine after the container is running? If not, what is the point of having anonymous volumes?

TL;DR: You can associate a specific anonymous volume with a running container via a 'data container', but that provides flexibility to cover a use case that is now much better served by the use of named volumes.

Anonymous volumes were helpful before the addition of volume management in Docker 1.9. Prior to that, you didn't have the option of naming a volume. With the 1.9 release, volumes became discrete, manageable objects with their own lifecycle.

Before 1.9, without the ability to name a volume, you had to reference it by first creating a data container

docker create -v /data --name datacontainer mysql

and then mounting the data container's anonymous volume into the container that needed access to the volume

docker run -d --volumes-from datacontainer --name dbinstance mysql

These days, it's better to use named volumes since they are much easier to manage and much more explicit.