Docker中使用Selenium启动Chrome报错org.openqa.selenium.SessionNotCreatedException
问题:Docker中Selenium Grid无法创建Chrome会话,连接超时
尝试在Docker环境下通过Selenium操控Chrome访问https://www.google.com/获取标题,执行时始终抛出会话创建失败异常,核心问题为连接超时。
抛出的异常
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure.
相关代码
测试代码
package remoteTesting.DockerValidation; import java.net.MalformedURLException; import java.net.URL; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; public class ChromeStandAloneTest { public static void main(String[] args) throws MalformedURLException { URL url = new URL("http://172.17.0.2:4444/wd/hub"); DesiredCapabilities cap =new DesiredCapabilities(); cap.setCapability("browserName","chrome"); WebDriver remoteWebDriver = new RemoteWebDriver(url,cap); remoteWebDriver.get("https://www.google.com/"); System.out.print(remoteWebDriver.getTitle()); } }
Selenium Maven依赖
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.10.0</version> </dependency>
Docker相关信息
Docker命令
- 拉取镜像:
docker pull selenium/standalone-chrome:latest - 启动容器:
docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-chrome:latest
Docker容器日志
[node] session-timeout = "300" override-max-sessions = false detect-drivers = false drain-after-session-count = 0 max-sessions = 1 [[node.driver-configuration]] display-name = "chrome" stereotype = '{"browserName": "chrome", "browserVersion": "114.0", "platformName": "Linux"}' max-sessions = 1 Starting Selenium Grid Standalone... Tracing is disabled 14:28:51.150 INFO [LoggingOptions.configureLogEncoding] - Using the system default encoding 14:28:51.212 INFO [OpenTelemetryTracer.createTracer] - Using OpenTelemetry for tracing 14:28:58.003 INFO [NodeOptions.getSessionFactories] - Detected 4 available processors 14:28:58.489 INFO [NodeOptions.report] - Adding chrome for {"browserName": "chrome","browserVersion": "114.0","platformName": "linux","se:noVncPort": 7900,"se:vncEnabled": true} 1 times (Host) 14:28:58.631 INFO [Node.<init>] - Binding additional locator mechanisms: relative 14:28:58.805 INFO [GridModel.setAvailability] - Switching Node 2b995240-198b-47f2-99c3-301922c9a38b (uri: http://172.17.0.2:4444) from DOWN to UP 14:28:58.808 INFO [LocalDistributor.add] - Added node 2b995240-198b-47f2-99c3-301922c9a38b at http://172.17.0.2:4444. Health check every 120s 14:28:59.873 INFO [Standalone.execute] - Started Selenium Standalone 4.10.0 (revision c14d967899): http://172.17.0.2:4444
完整错误堆栈
Jul 29, 2023 8:18:25 PM org.openqa.selenium.remote.tracing.opentelemetry.OpenTelemetryTracer createTracer INFO: Using OpenTelemetry for tracing SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. Host info: host: 'Pankajs-MacBook-Air.local', ip: 'fe80:0:0:0:838:973c:93b8:49da%en0' Build info: version: '4.10.0', revision: 'c14d967899' System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '13.4.1', java.version: '18.0.1.1' Driver info: org.openqa.selenium.remote.RemoteWebDriver Command: [null, newSession {capabilities=[Capabilities {browserName: chrome}]}] Capabilities {browserName: chrome} at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:549) at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:227) at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:154) at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:134) at remoteTesting.DockerValidation.ChromeStandAloneTest.main(ChromeStandAloneTest.java:16) Caused by: java.io.UncheckedIOException: java.net.ConnectException: connection timed out: /172.17.0.2:4444 at org.openqa.selenium.remote.http.netty.NettyHttpHandler.makeCall(NettyHttpHandler.java:73) at org.openqa.selenium.remote.http.AddSeleniumUserAgent.lambda$apply$0(AddSeleniumUserAgent.java:42) at org.openqa.selenium.remote.http.Filter.lambda$andFinally$1(Filter.java:55) at org.openqa.selenium.remote.http.netty.NettyHttpHandler.execute(NettyHttpHandler.java:48) at org.openqa.selenium.remote.http.AddSeleniumUserAgent.lambda$apply$0(AddSeleniumUserAgent.java:42) at org.openqa.selenium.remote.http.Filter.lambda$andFinally$1(Filter.java:55) at org.openqa.selenium.remote.http.netty.NettyClient.execute(NettyClient.java:97) at org.openqa.selenium.remote.tracing.TracedHttpClient.execute(TracedHttpClient.java:54) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:115) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:96) at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:68) at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:163) at org.openqa.selenium.remote.TracedCommandExecutor.execute(TracedCommandExecutor.java:51) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:531) ... 4 more Caused by: java.net.ConnectException: connection timed out: /172.17.0.2:4444 at org.asynchttpclient.netty.channel.NettyConnectListener.onFailure(NettyConnectListener.java:179) at org.asynchttpclient.netty.channel.NettyChannelConnector$1.onFailure(NettyChannelConnector.java:108) at org.asynchttpclient.netty.SimpleChannelFutureListener.operationComplete(SimpleChannelFutureListener.java:28) at org.asynchttpclient.netty.SimpleChannelFutureListener.operationComplete(SimpleChannelFutureListener.java:20) at io.netty.util.concurrent.DefaultPromise.notifyListener0(DefaultPromise.java:590) at io.netty.util.concurrent.DefaultPromise.notifyListeners0(DefaultPromise.java:583) at io.netty.util.concurrent.DefaultPromise.notifyListenersNow(DefaultPromise.java:559) at io.netty.util.concurrent.DefaultPromise.notifyListeners(DefaultPromise.java:492) at io.netty.util.concurrent.DefaultPromise.setValue0(DefaultPromise.java:636) at io.netty.util.concurrent.DefaultPromise.setFailure0(DefaultPromise.java:629) at io.netty.util.concurrent.DefaultPromise.tryFailure(DefaultPromise.java:118) at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe$1.run(AbstractNioChannel.java:262) at io.netty.util.concurrent.PromiseTask.runTask(PromiseTask.java:98) at io.netty.util.concurrent.ScheduledFutureTask.run(ScheduledFutureTask.java:153) at io.netty.util.concurrent.AbstractEventExecutor.runTask(AbstractEventExecutor.java:174) at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:167) at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:470) at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:569) at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:997) at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74) at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) at java.base/java.lang.Thread.run(Thread.java:833) Caused by: io.netty.channel.ConnectTimeoutException: connection timed out: /172.17.0.2:4444 at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe$1.run(AbstractNioChannel.java:261) ... 10 more
已尝试的解决方法
- 重启Docker
- 核对Selenium版本(本地与容器均为4.10.0)
解决方案
1. 修正Grid连接地址
代码中使用了容器内部IP 172.17.0.2,本地主机无法直接访问该地址。应替换为本地主机IP或localhost(容器端口已映射到主机):
URL url = new URL("http://localhost:4444/wd/hub");
Mac环境也可尝试使用host.docker.internal替代localhost。
2. 验证Grid服务可用性
在本地浏览器打开 http://localhost:4444/ui,若能看到Selenium Grid控制台,说明服务正常;若无法访问:
- 查看容器状态:
docker ps - 重启容器:
docker restart <容器ID>
3. 使用指定版本镜像(可选)
避免latest标签的不确定性,拉取与本地Selenium版本一致的镜像:
docker pull selenium/standalone-chrome:4.10.0 docker run -d -p 4444:4444 --shm-size="2g" selenium/standalone-chrome:4.10.0
4. 检查防火墙设置
Mac系统防火墙可能阻止本地到容器的连接,临时关闭防火墙测试是否恢复正常。
内容的提问来源于stack exchange,提问作者pankaj yadav
相关产品推荐
相关产品推荐

