Import docker compose file in another compose file

2020-08-25 07:13发布

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条回答
forever°为你锁心
2楼-- · 2020-08-25 07:42

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 even 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.

查看更多
登录 后发表回答