问题描述
docker build --tag house .
然后:docker run -it -p 5000:5000 house
返回错误:当我尝试通过 Postman 向 127.0.0.1:5000 发送 GET 请求时,connect ECONNREFUSED 127.0.0.1:5000
还有:
docker build --tag house .
然后:docker run --publish 5000:5000 house
返回错误:当我尝试通过 Postman 向 127.0.0.1:5000 发送 GET 请求时套接字挂断
我也试过 localhost:5000 和 0.0.0.0:5000。我能做些什么来让项目运行吗?
可以从这里克隆或分叉整个项目存储库(肯定有一些垃圾挂在外面,但核心文件 app.py、Dockerfile、model.py、model.pkl 都在那里):{{3} }
如果您想初步了解以下代码: 码头档案
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
app.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","--host=0.0.0.0"]