python - 错误:连接 ECONNREFUSED 127.0.0.1:5000 或错误:对 docker 容器的 GET 请求后套接字挂断
问题描述
docker build --tag house .
然后:docker run -it -p 5000:5000 house
返回错误:当我尝试通过 Postman 向 127.0.0.1:5000 发送 GET 请求时连接 ECONNREFUSED 127.0.0.1:5000
另外:
docker build --tag house .
然后:docker run --publish 5000:5000 house
返回错误:当我尝试通过邮递员向 127.0.0.1:5000 发送 GET 请求时,套接字挂断
我也试过 localhost:5000 和 0.0.0.0:5000。我能做些什么来让项目运行起来吗?
整个项目存储库可以从这里克隆或分叉(有一些垃圾挂出,但核心文件,app.py,Dockerfile,model.py,model.pkl 都在那里):https ://github.com /aliciachen10/wakecountyhousing_final
如果您想初步了解一下,下面是代码: DOCKERFILE
FROM ubuntu:18.04
RUN apt -y update &&\
apt -y install python3 python3-pip
ENV PYTHON_VERSION 3.9.4
COPY . .
RUN python3 -m pip install -r python_requirements.txt
EXPOSE 5000
CMD [ "python3", "-u", "./app.py" ]
python_requirements.txt 文件:
pandas
numpy
flask
scikit-learn
应用程序.py
import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle
app = Flask(__name__,template_folder='templates')
model = pickle.load(open('model.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict',methods=['POST'])
def predict():
int_features = [int(x) for x in request.form.values()]
final_features = [np.array(int_features)]
prediction = model.predict(final_features)
output = np.round(prediction[0], 2)
return render_template('index.html', prediction_text='Home price should be $ {}'.format(output))
@app.route('/results',methods=['POST'])
def results():
data = request.get_json(force=True)
prediction = model.predict([np.array(list(data.values()))])
output = prediction[0]
return jsonify(output)
if __name__ == "__main__":
#app.run(debug=True, host='0.0.0.0')
app.run(debug=True)
多谢你们!
解决方案
问题出在 Dockerfile 中的 CMD 命令中。
来自 Docker 文档:
“现在,我们要做的就是告诉 Docker,当我们的镜像在容器内执行时,我们想要运行什么命令。我们使用 CMD 命令执行此操作。请注意,我们需要使应用程序在外部可见(即从外部容器)通过指定--host=0.0.0.0。”
您需要提供 --host 参数并更改命令:
CMD ["python3", "-m", "flask", "run", "--host=0.0.0.0"]
此外,当我运行容器时,我收到一个与 UTF-8 相关的 RuntimeError。因此,您需要将以下 ENV 变量添加到 Dockerfile。
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8
最后,Dockerfile 看起来像这样:
FROM ubuntu:18.04
RUN apt -y update &&\
apt -y install python3 python3-pip
ENV PYTHON_VERSION 3.9.4
COPY . .
RUN python3 -m pip install -r python_requirements.txt
EXPOSE 5000
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8
CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
推荐阅读
- flutter - 如何创建一个 30 分钟的时间段。我从后端获取开始日期和结束日期
- c# - FlowPanel 中的多页 TIFF 参数无效
- reactjs - 如何在 Material-UI 中使用 mountOnEnter
- javascript - 有没有办法只在 JavaScript 中打印 JSON 字符串的一部分
- elasticsearch - ELASTICSEARCH - 如何根据不同级别的嵌套字段的值执行 update_by_query?
- android - 有什么方法可以确定在 adnroid 生物识别上使用了哪个 biometrick 提供程序?
- entity-framework-core - ASP.NET Core MVC 和 Entity Framework Core 中的计算
- python - 填充现有数组的最快方法
- reactjs - 开玩笑地获取元素的子元素
- django - 是否有类似 django-sphinxdoc 的包用于 django3.X 或如何使其与 django3.X 一起使用