docker-compose v3在多个容器之间共享相同的卷安装位置

时间:2017-05-17 12:50:53

标签: docker docker-compose

以前我使用volumes_from将多个卷位置挂载到多个容器,如下所示:

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

但是,在使用本机卷装入时,在docker-compose版本3中,volumes_from不可用,这导致我执行以下操作:

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

有没有什么方法可以将同一组卷挂载引用到多个服务,而不定义它们两次?

2 个答案:

答案 0 :(得分:1)

YAML支持"主播"重新使用位:(来自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

答案 1 :(得分:0)

这是一个docker-compose版本3示例,其中锚用于环境变量。

值在第一次使用时设置,然后在使用相同环境变量的任何其他服务中引用。

请注意在设置锚点时使用&amp; environment ,并在引用它时使用 * environment

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