Mark Shust at M.academy
Mark Shust at M.academy

Reputation: 6429

docker-compose v3 share the same volume mount locations between multiple containers

Previously I used volumes_from to mount multiple volume locations to multiple containers, like so:

app:
  image: mageinferno/magento2-nginx:1.11-1
  links:
    - phpfpm
  volumes_from:
    - appdata
  ports:
    - 8000:80

phpfpm:
  image: mageinferno/magento2-php:7.0-fpm-1
  links:
    - db
  volumes_from:
    - appdata

appdata:
  image: tianon/true
  volumes:
    - /var/www/html
    - ~/.composer:/var/www/.composer
    - ./html/app/code:/var/www/html/app/code
    - ./html/app/design:/var/www/html/app/design

However, in docker-compose version 3 when using native volume mounts, volumes_from is not available, which leads me to do something like this:

version: "3"

services:
  app:
    image: mageinferno/magento2-nginx:1.11-1
    links:
      - phpfpm
    volumes:
      - appdata:/var/www/html
      - ~/.composer:/var/www/.composer
      - ./html/app/code:/var/www/html/app/code
      - ./html/app/design:/var/www/html/app/design
    ports:
      - 8000:80

  phpfpm:
    image: mageinferno/magento2-php:7.0-fpm-1
    links:
      - db
    volumes:
      - appdata:/var/www/html
      - ~/.composer:/var/www/.composer
      - ./html/app/code:/var/www/html/app/code
      - ./html/app/design:/var/www/html/app/design

Is there any way I can reference the same group of volume mounts to multiple services, without defining them twice?

Upvotes: 0

Views: 963

Answers (2)

Here is a docker-compose version 3 example where an anchor is used for the environment variables.

The values are set the first time they are used, and then referenced in any additional services that use the same environment variables.

Note the use of &environment in setting the anchor, and *environment in referencing it.

version: '3'
services:
  ui:
    build:
      context: ./ui
    ports:
      - 80:80
      - 8080:8080
    networks:
      - cluster-net
    environment: &environment
      A_VAR: 'first-var'
      ANOTHER_VAR: 'second-var'
  api:
    build:
      context: ./api
    networks:
      - cluster-net
    environment: *environment

networks:
  cluster-net:
    driver: bridge

Upvotes: 0

Rawkode
Rawkode

Reputation: 22592

YAML supports "anchors" for re-using bits: (From https://learnxinyminutes.com/docs/yaml/)

# YAML also has a handy feature called 'anchors', which let you easily duplicate
# content across your document. Both of these keys will have the same value:
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name

# Anchors can be used to duplicate/inherit properties
base: &base
    name: Everyone has same name

foo: &foo
    <<: *base
    age: 10

bar: &bar
    <<: *base
    age: 20

Upvotes: 1

Related Questions