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

以前,我使用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 

有什么办法可以将同一组卷装入到多个服务中,而不用两次定义它们?

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 

这是一个docker-compose版本3的例子,其中一个锚点用于环境variables。

这些值在第一次使用时进行设置,然后在使用相同环境variables的其他服务中引用。

注意在设置锚点时使用&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