You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署Flask+Selenium服务报cannot open display: :0错误求助

Flask + Selenium 部署X server报错问题排查解决

问题背景

部署Flask应用实现用户输入链接后,调用Selenium脚本处理链接并返回对应信息。该功能数日前可正常运行,无明确人工变更下突然失效,用户输入URL触发Selenium运行时抛出X server配置相关错误。

初始报错日志

geckodriver运行日志如下:

1655398364982   geckodriver INFO    Listening on 127.0.0.1:60701
1655398365537   mozrunner::runner   INFO    Running command: "/usr/bin/firefox" "--marionette" "--remote-debugging-port" "57429" "--remote-allow-hosts" "localhost" "-no-remote" "-profile" "/tmp/rust_mozprofileqf4HKQ"
No protocol specified
Unable to init server: Could not connect: Connection refused
Error: cannot open display: :0

已尝试的无效操作

  • 尝试通过虚拟帧缓冲运行服务,未解决问题
  • 尝试将DISPLAY变量配置为服务器完整IP,原有报错未解决,新增Broadway显示类型不支持错误,对应日志如下:
1655398078139   geckodriver INFO    Listening on 127.0.0.1:60065
1655398078684   mozrunner::runner   INFO    Running command: "/usr/bin/firefox" "--marionette" "--remote-debugging-port" "48811" "--remote-allow-hosts" "localhost" "-no-remote" "-profile" "/tmp/rust_mozprofilelQkVrP"
Unable to init server: Broadway display type not supported: (my_servers_ip):0
Error: cannot open display: (my_servers_ip):0

当前服务启动方式

使用gunicorn启动服务,执行命令为:
/home/dummy/project/venv/bin/gunicorn --chdir /home/dummy/project -w 9 main:app


解决步骤

优先方案:使用Firefox无头模式(从根源规避X server依赖)

服务器部署Selenium优先选无头模式,不需要配置任何X服务、DISPLAY变量,稳定性最高。初始化WebDriver时添加对应参数即可:

from selenium.webdriver.firefox.options import Options
from selenium import webdriver

firefox_options = Options()
firefox_options.add_argument("--headless")
firefox_options.add_argument("--no-sandbox")
firefox_options.add_argument("--disable-dev-shm-usage")
# 可选:系统识别不到firefox时手动指定二进制路径
# firefox_options.binary_location = "/usr/bin/firefox"
driver = webdriver.Firefox(options=firefox_options)

注意:Firefox 56+版本支持--headless参数,旧版本需要替换为-headless

备选方案:正确配置虚拟帧缓冲(非无头场景使用)

之前虚拟帧缓冲方案失效基本是配置步骤缺失,按以下顺序操作:

  • 安装依赖组件
sudo apt update && sudo apt install -y xvfb x11-xkb-utils xfonts-100dpi xfonts-75dpi xfonts-scalable xfonts-cyrillic
  • 启动Xvfb服务,指定未被占用的显示端口(比如用99端口避开默认的0端口冲突)
Xvfb :99 -screen 0 1920x1080x24 &
  • 配置X服务访问权限,允许本地用户访问
xhost +local:
  • 启动gunicorn前显式指定DISPLAY环境变量,不要填服务器公网IP,直接指向本地虚拟显示端口:
DISPLAY=:99 /home/dummy/project/venv/bin/gunicorn --chdir /home/dummy/project -w 9 main:app

把DISPLAY设为服务器IP会报错的原因:服务器没有运行对外暴露的X11服务,也没有配置Broadway显示后端,必然返回类型不支持错误。

突发失效排查方向

如果之前配置正常突然失效,逐一排查以下点:

  • 检查系统是否自动更新升级了Firefox、geckodriver版本,版本不兼容会导致启动参数失效
  • 检查之前配置的Xvfb进程是否被意外终止、开机自启任务是否失效
  • 检查gunicorn启动用户是否变更,普通用户配置的X权限不会对root用户生效
  • 检查/tmp目录下的X11套接字文件是否被误删,权限配置是否正确

内容的提问来源于stack exchange,提问作者your_question_limit_has_been_r

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.30 05:42:13