How to set a path on host for a named volume in docker-compose.yml

DockerDocker ComposeDocker Volume

Docker Problem Overview


Example below creates dbdata named volume and references it inside db service:

version: '2'
services:
  db:
    image: mysql
    volumes:
      - dbdata:/var/lib/mysql
volumes:
  dbdata:
    driver: local

(from https://stackoverflow.com/a/35675553/4291814)

I can see the path for the volume defaults to:

/var/lib/docker/volumes/<project_name>_dbdata

My question is how to configure the path on host for the dbdata volume?

Docker Solutions


Solution 1 - Docker

With the local volume driver comes the ability to use arbitrary mounts; by using a bind mount you can achieve exactly this.

For setting up a named volume that gets mounted into /srv/db-data, your docker-compose.yml would look like this:

version: '2'
services:
  db:
    image: mysql
    volumes:
      - dbdata:/var/lib/mysql
volumes:
  dbdata:
    driver: local
    driver_opts:
      type: 'none'
      o: 'bind'
      device: '/srv/db-data'

I have not tested it with the version 2 of the compose file format, but https://docs.docker.com/compose/compose-file/compose-versioning/#version-2 does not indicate, that it should not work.

I've also not tested it on Windows...

Solution 2 - Docker

The location of named volumes is managed by docker; if you want to specify the location yourself, you can either "bind mount" a host directory, or use a volume plugin that allows you to specify a path.

You can find some details in another answer I posted recently; https://stackoverflow.com/a/36321403/1811501

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmishaView Question on Stackoverflow
Solution 1 - DockerChristian UlbrichView Answer on Stackoverflow
Solution 2 - DockerthaJeztahView Answer on Stackoverflow