Gunicorn命令行运行正常,systemd服务启动后端口无响应
Gunicorn WebSocket服务通过Systemd启动后端口无法访问的排查与解决
问题现象
- 直接在终端执行以下命令时,Gunicorn运行正常,8000端口可正常接收数据:
/ins/icenv/bin/gunicorn app.main:app --workers 1 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 --certfile=/ins/key_ls/fullchain.pem --keyfile=/ins/key_ls/privkey.pem --access-logfile /tmp/null --error-logfile /ins/logs/error_log_gunicorn_ws.log &
- 执行
sudo systemctl start gunicornws启动服务后,进程显示活跃,但8000端口无法对外提供服务。
最初的Systemd配置(异常状态)
Description=WebSocket Gunicorn Service After=network.target [Service] User=customuser Group=www-data WorkingDirectory=/instant_connection/ ExecStart=/ins/icenv/bin/gunicorn app.main:app --workers 1 --worker-class uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 --certfile=/ins/key_ls/fullchain.pem --keyfile=/ins/key_ls/privkey.pem --access-logfile /tmp/null --error-logfile /ins/logs/error_log_gunicorn_ws.log [Install] WantedBy=multi-user.target
备注说明
另有一个通过Unix套接字运行的Gunicorn实例,与Nginx配合正常;此次为内部需求,单独部署基于端口的WebSocket服务实例。
修改后的Systemd配置(恢复正常)
Description=WebSocket Gunicorn Service After=network.target [Service] User=jean15151352 Group=jean15151352 WorkingDirectory=/ins/ ExecStart=/ins/icenv/bin/gunicorn \ app.main:app \ --workers 1 \ --worker-class uvicorn.workers.UvicornWorker \ --bind 0.0.0.0:8000 \ --certfile=/ins/key_ls/fullchain.pem \ --keyfile=/ins/key_ls/privkey.pem \ --access-logfile /tmp/null \ --error-logfile /ins/logs/error_log_gunicorn_ws.log [Install] WantedBy=multi-user.target
关键修复点
- 工作目录修正:将
WorkingDirectory从/instant_connection/改为/ins/,确保Gunicorn启动时能正确定位到app.main模块路径。 - 权限配置调整:将运行服务的用户/组从
customuser:www-data改为jean15151352:jean15151352,解决用户对代码目录、证书文件及日志文件的访问权限问题。 - 命令格式优化:将
ExecStart单行命令拆分为多行(反斜杠换行),提升配置文件可读性,便于后续维护。
内容的提问来源于stack exchange,提问作者Jean-Christophe Bonnet
相关产品推荐
相关产品推荐

