多个 docker-compose 项目之间的通信 [英] Communication between multiple docker-compose projects

查看:57
本文介绍了多个 docker-compose 项目之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个不同的文件夹中有两个单独的 docker-compose.yml 文件:

  • ~/front/docker-compose.yml
  • ~/api/docker-compose.yml

如何确保front中的容器可以向api中的容器发送请求?

我知道可以使用 docker run 为单个容器设置 --default-gateway 选项,以便可以为该容器分配特定的 IP 地址,但是在使用 docker-compose 时,这个选项似乎不可用.

目前我最终做了一个 docker inspect my_api_container_id 并查看输出中的网关.它有效,但问题是这个 IP 是随机归属的,所以我不能依赖它.

这个问题的另一种形式可能是:

  • 我可以使用 docker-compose 将固定 IP 地址分配给特定容器吗?

但最终我要照顾的是:

  • 两个不同的 docker-compose 项目如何相互通信?

解决方案

您只需要确保要相互通信的容器位于同一网络上.网络是一流的 docker 构造,并不特定于组合.

# front/docker-compose.yml版本:'2'服务:正面:...网络:- 一些网网络:一些网:司机:桥

...

# api/docker-compose.yml版本:'2'服务:接口:...网络:-front_some-net网络:front_some-net:外部:真实

<块引用>

注意:您的应用程序网络的名称基于项目名称",该名称基于其所在目录的名称,在本例中添加了前缀 front_>

然后他们可以使用服务名称相互交谈.从front你可以做ping api,反之亦然.

I have two separate docker-compose.yml files in two different folders:

  • ~/front/docker-compose.yml
  • ~/api/docker-compose.yml

How can I make sure that a container in front can send requests to a container in api?

I know that --default-gateway option can be set using docker run for an individual container, so that a specific IP address can be assigned to this container, but it seems that this option is not available when using docker-compose.

Currently I end up doing a docker inspect my_api_container_id and look at the gateway in the output. It works but the problem is that this IP is randomly attributed, so I can't rely on it.

Another form of this question might thus be:

  • Can I attribute a fixed IP address to a particular container using docker-compose?

But in the end what I'm looking after is:

  • How can two different docker-compose projects communicate with each other?

解决方案

You just need to make sure that the containers you want to talk to each other are on the same network. Networks are a first-class docker construct, and not specific to compose.

# front/docker-compose.yml
version: '2'
services:
  front:
    ...
    networks:
      - some-net
networks:
  some-net:
    driver: bridge

...

# api/docker-compose.yml
version: '2'
services:
  api:
    ...
    networks:
      - front_some-net
networks:
  front_some-net:
    external: true

Note: Your app’s network is given a name based on the "project name", which is based on the name of the directory it lives in, in this case a prefix front_ was added

They can then talk to each other using the service name. From front you can do ping api and vice versa.

这篇关于多个 docker-compose 项目之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆