Docker部署.NET Core Api+Selenium Hub时WebDriver请求异常排查
问题详情
我打算用Docker部署包含以下组件的网站:
-.NET Core Api
-Chrome Driver
-Selenium Hub
通过docker-compose创建容器后无法正常运行,报错信息如下:
crit: Microsoft.AspNetCore.Hosting.Diagnostics[6]
Application startup exception
OpenQA.Selenium.WebDriverException: An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL http://localhost:4444/wd/hub/session. The exception message was: Cannot assign requested address (localhost:4444)
我的docker-compose配置文件:
version: "3" services: selenium-hub: image: selenium/hub container_name: selenium-hub ports: - "4444:4444" chrome: image: selenium/standalone-chrome volumes: - /dev/shm:/dev/shm depends_on: - selenium-hub environment: - HUB_HOST=selenium-hub - HUB_PORT=4444 web: build: . ports: - "8090:80"
项目中实例化WebDriver的代码:
ChromeOptions options = new ChromeOptions(); options.AddArgument("no-sandbox"); options.AddArgument("headless"); driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options);
已确认容器创建成功,selenium-hub服务正常启动:
selenium-hub | 08:31:29.415 INFO [Hub.execute] - Started Selenium Hub 4.3.0 (revision a4995e2c09*): http://192.168.80.3:4444
解决方法
问题根源确实是Uri设置错误。在Docker Compose的默认网络环境中,每个容器的localhost指向自身,而非宿主机或其他容器。Docker会自动将服务名称(这里是selenium-hub)作为可解析的域名映射到对应容器的IP地址。
只需修改实例化RemoteWebDriver的Uri,将localhost替换为服务名称selenium-hub即可:
ChromeOptions options = new ChromeOptions(); options.AddArgument("no-sandbox"); options.AddArgument("headless"); driver = new RemoteWebDriver(new Uri("http://selenium-hub:4444/wd/hub"), options);
额外提示:depends_on仅保证selenium-hub容器先启动,但不确保服务完全就绪。如果遇到服务未就绪导致的连接问题,可以添加健康检查或使用等待脚本,但当前场景下修改Uri即可解决核心问题。
内容的提问来源于stack exchange,提问作者Sasan

