我想将发布请求从一个容器发送到另一个容器,这两个都是烧瓶应用程序。
当我按下发送按钮的形式时,我的请求将无法发送,并显示错误:
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'))
我正在尝试仅在localhost上运行它。当我使用docker-compose up时,一切正常,直到我尝试发送请求为止。
app 1代码(app,我试图从中发送请求):
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"
我错过了什么?
答案 0 :(得分:2)
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)