Docker中运行Selenium卡在Started Selenium Standalone问题求助
问题分析与解决方案
你的问题核心是Python应用尝试连接Selenium服务时超时——虽然Selenium容器显示已启动,但实际服务可能尚未完全就绪,或配置存在兼容性问题。以下是针对性修复步骤:
1. 替换固定sleep为服务就绪等待机制(最关键)
depends_on仅保证容器启动顺序,不确保Selenium服务已准备好接受请求,固定sleep(5)完全不可靠。推荐两种解决方式:
方案A:给Selenium容器添加健康检查(优先选择)
修改docker-compose.yml,让App容器等待Selenium健康检查通过后再启动:
version: '3.3' services: selenium: image: selenium/standalone-chrome ports: - 4444:4444 restart: always healthcheck: test: ["CMD", "curl", "-f", "http://localhost:4444/wd/hub/status"] interval: 5s timeout: 10s retries: 5 app: build: context: . volumes: - ./app:/app command: sh -c "python3 bot.py" depends_on: selenium: condition: service_healthy
方案B:Python代码中添加重试逻辑
若不想修改docker-compose,可在代码中用动态重试替代固定sleep:
from time import sleep from selenium import webdriver from selenium.webdriver.chrome.options import Options from urllib3.exceptions import MaxRetryError chrome_options = Options() chrome_options.add_argument("--headless=new") # Selenium 4.10+推荐的无头模式 driver = None max_retries = 5 retry_count = 0 while retry_count < max_retries: try: driver = webdriver.Remote( command_executor='http://selenium:4444/wd/hub', options=chrome_options ) break except MaxRetryError: retry_count += 1 print(f"连接Selenium失败,重试第{retry_count}次...") sleep(3) if not driver: raise Exception("多次重试后仍无法连接Selenium服务") driver.get('https://python.org') driver.save_screenshot('screenshot.png') driver.quit() # 务必关闭驱动,避免资源泄漏
2. 替换过时的DesiredCapabilities配置
Selenium 4.x已废弃DesiredCapabilities的推荐用法,改用Options类可避免兼容性问题——上述代码已完成替换,并添加了适配新版本的无头模式参数。
3. 调整Selenium容器资源配置(可选)
Chrome在容器中运行需要足够共享内存,否则可能无响应。可给selenium容器增加共享内存配置:
services: selenium: image: selenium/standalone-chrome ports: - 4444:4444 restart: always shm_size: '2g' # 增加共享内存 healthcheck: test: ["CMD", "curl", "-f", "http://localhost:4444/wd/hub/status"] interval: 5s timeout: 10s retries: 5
4. 验证网络连通性(排查用)
若上述方法无效,可进入App容器测试与Selenium的连通性:
# 进入app容器 docker-compose exec app sh # 测试容器间网络可达性 ping selenium # 测试Selenium服务状态 curl http://selenium:4444/wd/hub/status
如果ping不通,检查Docker网络配置;如果curl返回错误,查看Selenium容器日志是否有异常。
内容的提问来源于stack exchange,提问作者NicoCaldo
相关产品推荐
相关产品推荐

