Ubuntu 18.04下systemd托管Selenium服务报ERR_CONNECTION_RESET,手动运行正常
问题原因与解决步骤
核心原因
手动启动gunicorn/Flask时,进程继承了你交互shell的所有环境变量,而systemd启动的服务不会加载用户目录下的~/.bashrc、~/.profile等配置,缺失代理相关环境变量,导致Chrome直连Google时被网络层重置连接,触发ERR_CONNECTION_RESET报错。
修复操作
- 先在你手动运行gunicorn的终端执行
env | grep -i proxy,记录所有代理配置项(包括HTTP_PROXY、HTTPS_PROXY、NO_PROXY等) - 编辑systemd服务文件:
sudo nano /etc/systemd/system/test.service,调整为以下配置(替换为你的实际路径和代理参数):[Unit] Description=Test Flask Service After=network.target [Service] User=chaoyang Group=chaoyang WorkingDirectory=/home/chaoyang/port8788 Environment="HOME=/home/chaoyang" # 替换为第一步查到的实际代理地址 Environment="HTTP_PROXY=你的代理地址" Environment="HTTPS_PROXY=你的代理地址" Environment="NO_PROXY=localhost,127.0.0.1" # 用Anaconda虚拟环境下的gunicorn绝对路径 ExecStart=/home/chaoyang/anaconda3/envs/selenium/bin/gunicorn --bind 0.0.0.0:5000 test:app Restart=always [Install] WantedBy=multi-user.target - 如果原有service配置里开启了
ProtectHome=yes、PrivateTmp=yes、ProtectSystem=strict这类沙箱限制,先注释后测试,避免Chrome无法访问临时目录或配置文件 - 重载配置并重启服务:
sudo systemctl daemon-reload sudo systemctl restart test - 调用
/test接口验证是否正常运行
额外修正项
- 你提供的Selenium代码中
def testDriver(url):下的options = Options()存在缩进错误,需修正为函数内缩进,否则会触发语法错误 - 可在Chrome options里添加临时用户目录参数,避免权限问题:
options.add_argument('--user-data-dir=/tmp/chrome-selenium-profile')
内容的提问来源于stack exchange,提问作者Chao-Yang Huang
相关产品推荐
相关产品推荐

