Import docker compose file in another compose file

时光总嘲笑我的痴心妄想 提交于 2020-03-18 15:35:55

问题


Is it possible to "import" or link a docker-compose file into another docker-compose file?

Suppose I have two files:

# docker-compose-1.yml
services:
    A:
        # config
    B:
        # config
# docker-compose-2.yml
services:
    C:
        # config
    import: docker-compose-1.yml

By running docker-compose -f docker-compose-2.yml up, I would like to start containers A, B (specified in the imported file) and C. Is this possible, without having to link both files with the -f parameter?


回答1:


By extending

It's possible to extend or use multiple docker-compose files and their services and link them in just one file. You can take a look at this link to understand how is the other usages of multiple compose files. But you can't include the file yet without link related files together as you mentioned.

Here I defined a common-services.yaml:

version: '2'
    services:
    nginx_a:
        image: nginx:latest
        container_name: nginx
        ports:
         - 81:80
         - 1443:443

And then I created a docker-compose.yml and included the common-services.yml file and its own service as well.

services:
   nginx:
     extends:
         file: common-services.yml
         service: nginx_a

   nginx_b:
      image: nginx:latest
      container_name: nginx_b
      volumes:
      ports:
       - 82:80
       - 2443:443

By .env technique

And if you want to avoid chaining usage of multiple files there is also a technique with .env files. I will rewrite the previous example with .env technique.

COMPOSE_PATH_SEPARATOR=:
COMPOSE_FILE=common-services.yml:docker-compose.yml

Let's add another service as an example in the common-services.yml

 version: '2'
 services:
   ngin_a:
     image: nginx:latest
     container_name: nginx_a
     ports:
       - 81:80
       - 1443:443

   redis_c:
     image: redis:latest
     container_name: redis_c
     ports:
       - 6381:6380

And Finally, load all of them in the docker-compose file without event mention to those services.

version: '2'
 services:
   nginx_b:
     image: nginx:latest
     container_name: nginx_b
     ports:
       - 82:80
       - 2443:443
     env_file:
       - .env

In the end, you will have three running services.



来源:https://stackoverflow.com/questions/55650342/import-docker-compose-file-in-another-compose-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!