如何修复"Failed to restart gunicorn.service: Unit gunicorn.socket not found."错误
问题根源
你的gunicorn.service配置中声明了依赖gunicorn.socket单元,但你没有创建对应的socket配置文件,systemd找不到该单元所以启动失败。你手动创建普通文件代替socket文件的操作无效,因为socket是特殊的进程通信文件,必须由systemd或gunicorn进程自动生成。
解决方案(二选一即可)
方案1:保留systemd socket激活机制(推荐)
socket激活的优势是仅在收到请求时才启动gunicorn进程,闲置时节省服务器资源,同时systemd会统一管理socket的权限、生命周期。
- 新建socket配置文件
/etc/systemd/system/gunicorn.socket,内容如下:
[Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock # 配置socket权限,方便Nginx等反向代理服务访问 SocketUser=www-data SocketGroup=www-data SocketMode=0660 [Install] WantedBy=sockets.target
- 重新加载systemd配置使其生效:
sudo systemctl daemon-reload
- 启动并设置开机自启socket单元:
sudo systemctl enable --now gunicorn.socket
- 此时再启动gunicorn服务即可正常运行:
sudo systemctl start gunicorn.service
- 验证运行状态:
sudo systemctl status gunicorn.socket gunicorn.service
方案2:删除socket依赖,直接启动gunicorn
如果你不需要socket激活功能,直接修改gunicorn.service配置即可:
- 打开
/etc/systemd/system/gunicorn.service,删除[Unit]段中的Requires=gunicorn.socket行 - 重新加载systemd配置:
sudo systemctl daemon-reload
- 直接启动gunicorn服务即可,gunicorn进程会自动生成对应的
sock文件:
sudo systemctl start gunicorn.service
内容的提问来源于stack exchange,提问作者Umut Çağdaş Coşkun
相关产品推荐
相关产品推荐

