Docker撰写:允许服务之间的网络交互

问题描述 投票:1回答:1

我想要两个Docker containers,它们在相同的docker-compose.yaml文件中定义,以便能够共享network并与彼此的暴露端口进行交互。我在Docker for Mac上运行所有这些。

为了做到这一点,我设置了几个运行一个小型Flask服务器的docker容器,它可以返回“Hello”或向另一台服务器发出请求(详见下文)。到目前为止,我一直无法允许这两个应用程序相互通信。

到目前为止我尝试过的:

  • exposeing相关的港口
  • publishing端口并与主机1:1映射
  • 对于flask使用localhost0.0.0.0作为--host arg
  • curl从一个容器到另一个容器(使用localhost:<other_container_port>0.0.0.0:<other_container_port>
  • 根据文档使用隐式network
  • 明确的network定义

所有上面的例子给我一个Connection Refused错误,所以我觉得我缺少一些关于Docker网络的基本知识。

Networking in Compose doc提到以下内容:

当您运行docker-compose时,会发生以下情况:

...

  1. 使用db的配置创建容器。它以名称db加入网络myapp_default。

他们的例子似乎让所有单独的服务能够在没有任何网络定义的情况下进行通信,这使我相信我可能不需要定义网络。

下面是我的docker-compose.yaml文件 - 所有文件都可以在this gist找到:

version: '3'
services:
    receiver:
        build: ./app
        # Tried with/without expose
        expose:
            - 3000
        # Tried with/without ports
        ports:
            - 3000:3000
        # Tried with/without 0.0.0.0
        command: "--host 0.0.0.0 --port 3000"
        # Tried with/without explicit network
        networks:
          - mine
    requester:
        build: ./app
        expose:
            - 4000
        ports:
            - 4000:4000
        # This one's ip is 0.0.0.0, so we can access from host
        command: "--host 0.0.0.0 --port 4000"
        networks:
          - mine
networks:
  mine: {}

app.py文件:

@app.route("/")
def hello():
    return "Hello from {}".format(request.host)

@app.route("/request/<int:port>")
def doPing(port):
     location = "http://localhost:{}/".format(port)
     return requests.get(location, timeout=5).content
python macos docker networking docker-compose
1个回答
2
投票

在docker-compose中,同一网络上的服务可以通过其名称相互访问,您甚至不必将端口暴露给主机。所以你的docker-compose.yaml可以简化为:

version: '3'
services:
receiver:
    build: ./app
    command: "--host 0.0.0.0 --port 3000"
requester:
    build: ./app
    command: "--host 0.0.0.0 --port 4000"

在容器请求者中,你可以访问另一个

ping receiver

解析名称,您可以验证端口是否也打开,例如使用netcat

nc -z receiver 3000 -v
© www.soinside.com 2019 - 2024. All rights reserved.