如何从连接到外部网络的另一个组合访问容器? [英] How to access container from another compose that connected to external network?

查看:112
本文介绍了如何从连接到外部网络的另一个组合访问容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我希望从外部容器连接到容器的配置文件(在另一个撰写文件中定义):

Here is compose file with config of container that I wish to connect to from external container (defined in another compose file):

version: '3.5'
services:
  service-to-connect-to:
    build: .
    networks:
      - my-external-network

networks:
  my-external-network:
    external: true

和另一个组成文件,其中包含我要从中连接到 service-to-connect-到

and another compose file that contains config for container from which I wish to connect to service-to-connect-to:

version: "3.5"

services:
  service-to-connect-from:
    build: .

我尝试连接到 service-to-connect-to 通过以下域:

I tried to connect to service-to-connect-to via this domains:

服务连接到
服务连接到我的外部网络
my_external_network。服务连接到

,但它们都不起作用。

我错了吗?

谢谢

推荐答案

首先,必须将两个服务都添加到同一网络才能连接它们。因此,后者的撰写文件应类似于

First, you have to add both services to same network in order to connect them. So, the latter compose file should be something like

version: "3.5"

services:
  service-to-connect-from:
    build .
    networks:
      - my-external-network

networks:
  my-external-network:
    external: true

现在,两个服务都在同一网络上,它们可以使用容器的名称相互查找。默认情况下,容器名称与服务名称相同,但docker compose还会在其前面加上项目名称作为前缀,默认情况下,该名称是组成文件所在的目录名称。如果首先通过 docker-compose up -d 启动服务,然后查看通过运行 docker ps命名容器的方式,则可以看到此信息。 code>。容器名称可以是例如 project1_service-to-connect-to 。使用该名称,您可以从其他服务连接。

Now that both services are on the same network they can find each other using container's name. Container name is by default same as the service name BUT docker compose also prefixes it by project name which is by default the directory name where the compose file exists. You can see this if you first start the services by docker-compose up -d and then see how the containers get named by running docker ps. The container name could be for example project1_service-to-connect-to. With this name you can connect from another service.

如果愿意,还可以使用 container_name 服务选项。使用时,compose不再以容器名称作为前缀。

If you like to, you can also set the container's name explicitly using container_name option for service. When used, compose doesn't prefix the container name anymore.

这篇关于如何从连接到外部网络的另一个组合访问容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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