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

如何在同一docker-compose中连接远程Selenium驱动并解决连接报错问题

问题修复方案
  • 核心原因是depends_on仅保证容器启动顺序,不会等待chromedriver内部的Selenium服务完全就绪,runner启动时Selenium还未完成4444端口的监听,因此触发连接拒绝报错。

具体修改步骤

步骤1:为chromedriver服务添加健康检查

修改docker-compose.yml中chromedriver的配置,增加健康检查逻辑,验证Selenium服务是否真正可用:

chromedriver:
  image: selenium/standalone-chrome
  ports:
    - "4444:4444"
  hostname: chromedriver
  shm_size: 2g
  # 新增以下健康检查配置
  healthcheck:
    test: ["CMD", "curl", "-f", "http://localhost:4444/wd/hub/status"]
    interval: 5s
    timeout: 3s
    retries: 10

步骤2:修改runner的启动依赖条件

将runner的depends_on配置修改为等待chromedriver服务健康后再启动:

runner:
  image: "kevoooo/twitchfarm-runner:latest"
  entrypoint: "python3 /py-scripts/main.py"
  healthcheck:
      test: python3 /py-scripts/main.py
      interval: 30s
      timeout: 10s
      retries: 5
  environment:
    - DISPLAY=127.0.0.1
    - USER=uname
    - PASS=pass
    - 2FA_KEY=key
  volumes:
    - "chrome-data:/saves/google-chrome"
  # 修改此处依赖配置
  depends_on:
    chromedriver:
      condition: service_healthy

备选补充方案

如果不想修改docker-compose配置,也可以在Python代码中增加连接重试逻辑,避免首次连接失败:

from time import sleep
from selenium.common.exceptions import WebDriverException

max_retries = 5
retry_count = 0
driver = None
while retry_count < max_retries:
    try:
        driver = webdriver.Remote(
            command_executor='http://chromedriver:4444/wd/hub',
            options=options
        )
        break
    except WebDriverException:
        retry_count += 1
        sleep(3)
if not driver:
    raise Exception("Selenium驱动连接失败")

其他排查点

  • 执行docker logs <chromedriver容器ID>查看Selenium容器启动日志,确认是否存在镜像拉取失败、启动崩溃等异常
  • 确认docker-compose没有自定义专属网络,两个服务默认处于同一网络下可正常解析hostname
  • 若使用Selenium 4.x版本,可尝试将连接地址改为http://chromedriver:4444,部分新版本已移除/wd/hub路径的强制要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:36:03