首页 > 解决方案 > “最大重试次数超出 URL”,两个 Docker 容器相互发送 POST 请求,在 localhost 上运行

问题描述

我在 localhost 上的两个独立 Docker 容器上运行两个 Flask 应用程序,使用端口映射3000:30005000:5000. 它们每个都有一个接受 POST 请求并执行某些功能的路由。这是应用程序 1 的代码:

@app.route('/preprocess', methods=['POST'])
def app_preprocess():
    req_data = request.get_json()

    bucket = req_data['bucket']
    input_file = req_data['input']
    upload_file = input_file + "_1"

    # do some functions

    to_send = {"bucket": bucket, "input": upload_file}
    to_send_string = json.dumps(to_send)

    requests.post("http://127.0.0.1:3000/postprocess", json=to_send_string)
    return "Sent request to 2"

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=5000)

和应用程序 2:

@app.route('/postprocess', methods=['POST'])
def app_postprocess():
    req_data = request.get_json()

    bucket = req_data['bucket']
    input_file = req_data['input']
    upload_file = input_file + "_2"

    # do some functions

    return "Uploaded 2"

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=3000)

我使用 Postman 将 POST 请求分别发送到每个应用程序。应用程序 1 和 2 都完成了它的工作(“执行某些功能”位)。App 2 会很好地返回“Uploaded 2”。

App 1 在该部分停止requests.post,并返回错误:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=3000): Max retries exceeded
        with url: /postprocess (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at
        0x7f74d3fc6b10>: Failed to establish a new connection: [Errno 111] Connection refused')) // Werkzeug Debugger

请帮忙解决这个问题,谢谢。另外我是 Flask 和 HTTP 路由的新手,所以我可能会错过一些东西。

编辑:这是 docker-compose.yaml

version: '3'
services:

  uploader-1:
    build: ./uploader-1
    image: uploader-1
    container_name: uploader-1
    ports:
        - 5000:5000

  uploader-2:
    build: ./uploader-2
    image: uploader-2
    container_name: uploader-2
    ports:
        - 3000:3000

标签: pythondockerflaskdocker-composehttp-post

解决方案


所以当你创建一个 docker 实例时,它会在你的机器上创建一个虚拟网络——所以每个 docker 实例都认为 127.0.0.1(或 localhost)是它本身,而不是你的实际计算机(认为是 127.0.0.1)。出于这个原因,您应该查看 docker 网络,或者

a)引用您要连接到的 docker 实例,或 b)添加一个端口(这是您所做的)然后引用父计算机 ip。

看这里的第二个答案:How to get the IP address of the docker host of the docker container from inside a docker container


推荐阅读