gpt4 book ai didi

python-3.x - docker 。无法建立新连接 : [Errno 111] Connection refused'

转载 作者:行者123 更新时间:2023-12-02 18:59:59 26 4
gpt4 key购买 nike

我想将 post 请求从一个容器发送到另一个容器,两者都是 Flask 应用程序。

当我按下表单中的发送按钮时,我的请求无法发送并出现错误:

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

我试图在本地主机上运行它。当我使用 docker-compose up 时,一切正常,直到我尝试发送请求。

应用程序 1 代码(应用程序,我试图从中发送请求):
from settings import app, db
from flask import jsonify, request
from models import User

@app.route('/users/', methods=['POST'])
def users_post():
if request.json:
new_user = User(
email=request.json['email'],
first_name=request.json['first_name'],
last_name=request.json['last_name'],
password=request.json['password'])

db.session.add(new_user)
db.session.commit()
return jsonify({'msg': 'user succesfully added'})
else:
return jsonify({'msg': 'request should be in json format'})



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

dockerfile 容器 1:
FROM python:3

COPY . ./app

WORKDIR /app

RUN pip3 install -r requirements.txt

EXPOSE 5000 5050

CMD ["python3", "app.py"]

应用程序2代码:
@app.route('/', methods=['GET', 'POST'])
def users_get():
if request.method == 'POST':
request.form['email']
data = {
'email':request.form['email'],
'first_name':request.form['first_name'],
'last_name':request.form['last_name'],
'password':request.form['password']
}
r = requests.post('http://0.0.0.0:5000/users/', data=data)
print(r.text)
return render_template('index.html')

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5050)

应用程序 2 中的 dockerfile 与第一个类似。

docker-compose
version: '3'

services:
web:
build: ./core
command: python3 app.py
volumes:
- .:/core
ports:
- "5000:5000"
links:
- new_app

new_app:
build: ./new_app
command: python3 app.py
volumes:
- .:/new_app
ports:
- "5050:5050"

我错过了什么?

最佳答案

  • app1 缺少端口,您应该添加它:
    app.run(debug=True, host='0.0.0.0', port=5000)
  • 当从 app2 调用 app1 时,你应该使用它的主机而不是 0.0.0.0 :
    r = requests.post('http://web:5000/users/', data=data)
  • 关于python-3.x - docker 。无法建立新连接 : [Errno 111] Connection refused',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61466799/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com