本地Socket.IO聊天应用Heroku部署失败,需配置Gunicorn+Gevent
Hey Roman, glad you narrowed down the issue to the app startup configuration—let's get your Socket.IO chat app running smoothly on Heroku while supporting up to 1000 concurrent connections!
1. Update Your Procfile
Your current Procfile uses the default Gunicorn worker, which doesn't handle WebSocket connections (required for Socket.IO) properly. Replace it with the Gevent WebSocket worker:
web: gunicorn -k geventwebsocket.gunicorn.workers.GeventWebSocketWorker -w 1 adult_main:app
-k geventwebsocket.gunicorn.workers.GeventWebSocketWorker: This worker is purpose-built to handle WebSocket traffic, which is essential for Socket.IO functionality.-w 1: Since Gevent uses coroutines instead of threads/processes, a single worker is sufficient to handle your 1000 connection target (Heroku dynos work best with this setup for Gevent-based apps).
2. Ensure All Dependencies Are in requirements.txt
You mentioned you already installed Gevent, but make sure you also include gevent-websocket (it's a separate package needed for the WebSocket worker). Update your requirements.txt to include:
Flask-SocketIO==2.9.6 gunicorn==19.7.1 gevent==21.12.0 gevent-websocket==0.10.1
(Note: These versions are compatible with Flask-SocketIO 2.9.6—feel free to adjust to newer compatible versions if needed.)
3. Verify Socket.IO Initialization in Your App
In adult_main.py, double-check that you're initializing Socket.IO with the Gevent async mode:
from flask import Flask from flask_socketio import SocketIO app = Flask(__name__) # Explicitly set async_mode to 'gevent' to match your worker setup socketio = SocketIO(app, async_mode='gevent') # Rest of your app logic...
This ensures Flask-SocketIO uses Gevent's async capabilities, matching the worker you're using in Gunicorn.
4. Test the Deployment
After pushing these changes to Heroku, verify the app works by:
- Running
heroku logs --tailto check for any startup errors (look for messages confirming the Gevent WebSocket worker is loaded). - Trying to connect to your chat app—Socket.IO should now establish a WebSocket connection successfully.
With these changes, your app should handle up to 1000 concurrent Socket.IO connections on Heroku without issues!
内容的提问来源于stack exchange,提问作者Roman

