解决 Gunicorn 报错 WORKER TIMEOUT 工作进程同步阻塞被杀修复
排查 Gunicorn 日志频繁输出 [CRITICAL] WORKER TIMEOUT (pid:xxxx),Worker 进程被主进程强制 kill 并重启,分析 同步代码慢查询与工作模式不匹配。
问题现象
Gunicorn 日志频繁记录工作进程超时并被主进程杀死:
[2026-11-16 10:14:02 +0800] [1521] [CRITICAL] WORKER TIMEOUT (pid:1530)
[2026-11-16 10:14:02 +0800] [1530] [INFO] Worker exiting (pid: 1530)
[2026-11-16 10:14:03 +0800] [1542] [INFO] Booting worker with pid: 1542
触发根因
- 默认的 sync 同步 Worker 遇到耗时较长的阻塞操作(如超大文件导出、未加索引的耗时 SQL 或下游慢 API 调用),阻塞时间超过了 Gunicorn 默认的 30 秒超时阈值;
- Worker 进程心跳同步文件(位于
/tmp或内存盘)由于系统 I/O 阻塞无法按时更新。
解决步骤
针对高 I/O 业务切换异步或多线程 Worker 模型
在 Gunicorn 启动命令中改用 gthread 或 gevent 模型:
gunicorn app:wsgi_app --workers 4 --worker-class gthread --threads 4 --timeout 60
适度延长 timeout 配置(针对重负载接口)
在 gunicorn.conf.py 配置文件中设置:
bind = "0.0.0.0:8000"
workers = 4
timeout = 120
graceful_timeout = 30
keepalive = 5
将 worker 临时心跳文件指向共享内存盘
避免宿主机磁盘 I/O 压力导致心跳写阻塞:
gunicorn --worker-tmp-dir /dev/shm app:wsgi_app
验证确认
重启 Gunicorn:
监控观察日志,工作进程在遇到重载任务时正常平稳完成,不再被主进程触发超时终止。


