在Google Colab中创建Flask应用遇连接拒绝错误,如何解决?
在Colab中部署Sklearn Pipeline模型时Flask-Ngrok连接失败的解决方法
我正在Google Colab笔记本中基于sklearn pipeline开发机器学习模型,并尝试将其部署。使用了以下代码:
import tensorflow_datasets as tfds import tensorflow as tf from flask import Flask, jsonify, make_response, request from flask_ngrok import run_with_ngrok app = Flask(__name__) run_with_ngrok(app) padding_size = 1000 model = pipeline print('Model and Vocabalory loaded.......') @app.route("/") def hello(): return "I am alive!" if __name__ == '__main__': app.run()
运行后遇到如下错误:
Model and Vocabalory loaded....... Serving Flask app 'main' Debug mode: off INFO:werkzeug:WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. Running on http://127.0.0.1:5000 INFO:werkzeug:Press CTRL+C to quit Exception in thread Thread-17: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/urllib3/connection.py", line 203, in _new_conn sock = connection.create_connection( File "/usr/local/lib/python3.10/dist-packages/urllib3/util/connection.py", line 85, in create_connection raise err File "/usr/local/lib/python3.10/dist-packages/urllib3/util/connection.py", line 73, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/urllib3/connectionpool.py", line 791, in urlopen response = self._make_request( File "/usr/local/lib/python3.10/dist-packages/urllib3/connectionpool.py", line 497, in _make_request conn.request( File "/usr/local/lib/python3.10/dist-packages/urllib3/connection.py", line 395, in request self.endheaders() File "/usr/lib/python3.10/http/client.py", line 1278, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.10/http/client.py", line 1038, in _send_output self.send(msg) File "/usr/lib/python3.10/http/client.py", line 976, in send self.connect() File "/usr/local/lib/python3.10/dist-packages/urllib3/connection.py", line 243, in connect self.sock = self._new_conn() File "/usr/local/lib/python3.10/dist-packages/urllib3/connection.py", line 218, in _new_conn raise NewConnectionError( urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x79d8a4408b80>: Failed to establish a new connection: [Errno 111] Connection refused The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/usr/local/lib/python3.10/dist-packages/requests/adapters.py", line 486, in send resp = conn.urlopen( File "/usr/local/lib/python3.10/dist-packages/urllib3/connectionpool.py", line 845, in urlopen retries = retries.increment( File "/usr/local/lib/python3.10/dist-packages/urllib3/util/retry.py", line 515, in increment raise MaxRetryError(_pool, url, reason) from reason # type: ignore[arg-type] urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='localhost', port=4040): Max retries exceeded with url: /api/tunnels (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x79d8a4408b80>: Failed to establish a new connection: [Errno 111] Connection refused')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 1378, in run self.function(*self.args, **self.kwargs) File "/usr/local/lib/python3.10/dist-packages/flask_ngrok.py", line 70, in start_ngrok ngrok_address = _run_ngrok() File "/usr/local/lib/python3.10/dist-packages/flask_ngrok.py", line 35, in _run_ngrok tunnel_url = requests.get(localhost_url).text # Get the tunnel information File "/usr/local/lib/python3.10/dist-packages/requests/api.py", line 73, in get return request("get", url, params=params, **kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/api.py", line 59, in request return session.request(method=method, url=url, **kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/sessions.py", line 589, in request resp = self.send(prep, **send_kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/sessions.py", line 703, in send r = adapter.send(request, **kwargs) File "/usr/local/lib/python3.10/dist-packages/requests/adapters.py", line 519, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=4040): Max retries exceeded with url: /api/tunnels (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x79d8a4408b80>: Failed to establish a new connection: [Errno 111] Connection refused'))
解决方法
1. 确保Ngrok正确安装并配置Auth Token
flask_ngrok依赖Ngrok服务,但Colab环境默认没有正确初始化Ngrok,需要手动完成以下步骤:
- 安装flask-ngrok(如果未安装):
!pip install flask-ngrok - 下载并解压Ngrok二进制文件:
!wget https://bin.equinox.io/c/bNyj1mQVY4c/ngrok-v3-stable-linux-amd64.tgz !tar -xvzf ngrok-v3-stable-linux-amd64.tgz - 设置Ngrok Auth Token(需从Ngrok官网获取免费token):
!./ngrok config add-authtoken YOUR_AUTH_TOKEN
2. 改用Pyngrok替代Flask-Ngrok(更稳定)
pyngrok是官方维护的Ngrok Python库,兼容性更好,步骤如下:
- 安装pyngrok:
!pip install pyngrok - 修改部署代码:
from flask import Flask, jsonify, make_response, request from pyngrok import ngrok app = Flask(__name__) # 启动Ngrok隧道,指向Flask默认的5000端口 public_url = ngrok.connect(5000).public_url print(f"可访问的公网URL: {public_url}") padding_size = 1000 model = pipeline # 确保此处的pipeline已完成训练和加载 print('Model and Vocabulary loaded.......') @app.route("/") def hello(): return "I am alive!" if __name__ == '__main__': app.run()
3. 检查端口占用(可选)
如果仍有问题,检查5000端口是否被占用:
!lsof -i :5000
若有占用进程,可通过kill命令终止,但Colab环境中这种情况极少出现。
内容的提问来源于stack exchange,提问作者Shalini Raghuram
相关产品推荐
相关产品推荐

