无法访问实验室服务器上Flask部署的模型,求问题排查指导
问题
我正遵循一篇教程在实验室服务器上部署机器学习模型,供实验室成员试用。教程部署的是用于预测销售额的Logistic regression模型,我认为该方案也适用于我的场景。
完整代码
- 服务器端代码(
app.py):部署在实验室服务器上,依赖序列化模型model.pkl和GUI页面index.html
import numpy as np from flask import Flask, request, jsonify, render_template import pickle app = Flask(__name__) 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 = round(prediction[0], 2) return render_template('index.html', prediction_text='Sales 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=False, host='0.0.0.0')
- 本地请求代码(
request.py):运行在本地机器
import requests data = {'rate':5, 'sales_in_first_month':200, 'sales_in_second_month':400} url = "http://<ip-address>/results" r = requests.post( url, json=data ) print(r.json())
问题现象
在实验室服务器执行python app.py启动应用(实际IP已替换为<ip-address>),服务器日志显示:
* Serving Flask app 'app' * Debug mode: off WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://<ip-address>:5000
但本地执行python request.py时始终无法访问服务器,无任何响应。登录实验室服务器需要用户名和密码,不确定访问模型是否需要凭证,原本以为知晓IP即可交互,想知道哪里操作有误。
解决思路
- 补全请求URL的端口号:Flask默认运行在5000端口,本地
request.py中的URL缺少端口,应修改为http://<ip-address>:5000/results。 - 检查服务器端口是否开放:实验室服务器的防火墙/安全组可能未对外开放5000端口。可在服务器上执行
nc -zv <服务器IP> 5000测试端口可用性;若未开放,联系管理员添加5000端口的入站规则,或临时关闭防火墙测试(仅用于排查)。 - 验证网络可达性:先在本地ping服务器IP,确认网络连通。若ping不通,说明本地与实验室服务器不在同一网络(比如服务器在内网、本地在外网),需通过VPN接入实验室内网,或配置端口转发。
- 确认服务器绑定IP有效性:确保
<ip-address>是服务器对外可访问的内网/公网IP,而非本地回环地址(127.0.0.1)。app.run(host='0.0.0.0')的配置是正确的,代表绑定所有网卡。 - 测试身份验证需求:若服务器有HTTP Basic Auth验证机制,可在
request.py中添加认证信息:r = requests.post(url, json=data, auth=('你的服务器用户名', '密码')) - 查看服务器防火墙状态:Ubuntu系统执行
ufw status,CentOS系统执行firewall-cmd --list-all,确认5000端口是否被允许入站。
内容的提问来源于stack exchange,提问作者Mr.Robot
相关产品推荐
相关产品推荐

