Docker部署Python WebSocket客户端无响应问题求助
问题
本地运行client.py脚本时一切正常,但通过Dockerfile构建镜像后,容器无任何日志输出(连初始的“Starting WebSocket connection.”都不显示),进程陷入停滞;使用docker-compose部署时,容器创建后停留在“Attaching to test-client-1”阶段无进展。
相关代码及配置如下:
Python脚本 client.py
import websocket import time def on_message(ws, message): print(f"Message received: {message}") def on_error(ws, error): print(f"Error: {error}") def on_close(ws): print("WebSocket connection closed.") def on_open(ws): print("WebSocket connection opened.") def run_websocket(): print("Starting WebSocket connection.") websocket_url = "wss://websocket-url" ws = websocket.WebSocketApp( url=websocket_url, on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close, ) while True: try: ws.run_forever() except Exception as e: print(f"WebSocket error: {e}") time.sleep(5) if __name__ == "__main__": run_websocket()
Dockerfile
FROM python:3.11-slim WORKDIR /app COPY . . RUN pip install --no-cache-dir -t requirements.txt CMD ["python", "client.py"]
docker-compose.yml
services: test-client: build: .
排查思路
- 修正依赖安装命令:Dockerfile里的
pip install --no-cache-dir -t requirements.txt参数错误,-t是指定安装目录,正确读取requirements文件的参数是-r,应改为RUN pip install --no-cache-dir -r requirements.txt。这个错误会导致依赖未正确安装,脚本启动失败但无输出。 - 禁用Python输出缓冲:容器环境中Python默认缓冲标准输出,
print内容不会实时显示。修改启动命令为CMD ["python", "-u", "client.py"],或者在脚本的每个print后添加sys.stdout.flush()(需先导入sys),强制刷新输出。 - 进入容器手动调试:执行
docker run -it --entrypoint /bin/bash <镜像名>进入容器终端,手动运行python client.py查看具体报错,同时用pip list检查依赖是否安装、ls确认requirements.txt是否存在。 - 测试容器网络连通性:在容器内执行
curl -v wss://websocket-url,确认能否访问目标WebSocket地址。如果目标是本地服务,需检查容器网络模式(比如用host模式)或使用正确的主机IP。 - 查看容器状态与日志:用
docker ps -a确认容器是否处于运行状态,用docker logs <容器ID>强制拉取日志,即使容器无实时输出,也可能获取启动失败的错误信息。 - 检查依赖包正确性:确认
requirements.txt中是websocket-client而非websocket——你的脚本依赖的是websocket-client库提供的websocket模块,依赖包名写错会导致安装后仍无法运行。
内容的提问来源于stack exchange,提问作者Springsomfan
相关产品推荐
相关产品推荐

