我正在本地主机上的两个单独的Docker容器上运行两个Flask应用程序,并使用端口映射3000:3000和5000: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)我使用邮递员分别向每个应用程序发送邮件请求。应用程序1和2都完成了它的工作(“做一些功能”比特)。应用程序2会很好地返回“上传的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路由的新手,所以我可能会错过一些东西。
编辑:这是码头-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发布于 2021-01-14 16:53:36
因此,当您创建一个对接实例时,它会在您的计算机上创建一个虚拟网络--因此每个对接实例都认为127.0.0.1 (或本地主机)是它自己,而不是您的实际计算机(您认为的是127.0.0.1)。由于这个原因,您应该查看docker网络,并且
( a)引用要连接到的坞实例,或( b)添加一个端口(这就是您所做的),然后引用父机器ip。
看这里的第二个答案:如何从码头容器内获取码头主机的IP地址
发布于 2020-07-20 08:07:23
您有两个单独的容器,其中应用程序运行在端口5000在第一个端口和3000端口在第二个端口。
当您从运行app 5000端口的第一个容器中发送请求时,您将得到requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=3000)。
这是因为在3000上的第一个容器中没有运行应用程序。
每个容器的localhost是不同的,并且它与docker主机的localhost不同。
如果您想以这种方式发送请求,则需要通过将network: host添加到停靠库组合中,从而允许容器进入network: host堆栈:
uploader-2:
build: ./uploader-2
image: uploader-2
container_name: uploader-2
network: host
ports:
- 3000:3000另一个更好的选择是连接到主机名,这些主机名是容器名称。
来自文档
默认情况下,Compose为您的应用程序设置一个网络。服务的每个容器都加入了默认网络,并且可以被网络上的其他容器访问,并且可以在主机名与容器名称相同的主机名上被发现。
所以代码看起来是:
requests.post("http://uploader-2:3000/postprocess", json=to_send_string)
甚至,更好的选择是向服务名称发送请求。这是有可能这样做的码头组成或码头群
任何服务都可以以该服务的名称到达任何其他服务
发布于 2021-01-14 16:38:58
错误来自IP地址127.0.0.1的使用。
Docker引入了一个虚拟网络,所以每个停靠者都认为自己是127,而不是主机。
(thx @Jmons)
要在本地启动代码,使用固定的IPv4地址。
对于Windows :打开命令提示符(cmd)并运行ipconfig命令,检索IP@,它位于IPv4 address. . . . . . . . . . . . . .:,通常为192.168.x.x类型
https://stackoverflow.com/questions/62988296
复制相似问题