首页 > 解决方案 > 错误:连接 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)

多谢你们!

标签: pythondockerflasknetworkingget

解决方案


问题出在 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"]

来源:https ://docs.docker.com/language/python/build-images/


推荐阅读