CodexBloom - Programming Q&A Platform

Selenium WebDriver throwing invalid session ID scenarios when using remote WebDriver with Docker

šŸ‘€ Views: 27 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-30
selenium-webdriver docker remotewebdriver Java

I need help solving I've searched everywhere and can't find a clear answer. I'm stuck on something that should probably be simple. I'm trying to run Selenium tests using a remote WebDriver instance hosted in a Docker container. Everything was working fine until recently when I started working with an `invalid session ID` behavior intermittently. Here's the relevant part of my setup: ```java WebDriver driver = new RemoteWebDriver( new URL("http://localhost:4444/wd/hub"), new ChromeOptions() ); ``` The tests connect to the Selenium Grid running in Docker. I've also set up my `docker-compose.yml` like this: ```yaml automation: image: selenium/standalone-chrome:4.0.0 ports: - "4444:4444" restart: always ``` After executing the tests, I sometimes see this behavior in my logs: ``` org.openqa.selenium.SessionNotFoundException: invalid session id ``` I've tried increasing the timeout for session creation, but it hasn't resolved the scenario. Additionally, I’m running a couple of tests in parallel which might be contributing to this question, but I’m using a ThreadLocal variable for my WebDriver instance: ```java private static ThreadLocal<WebDriver> driver = new ThreadLocal<>(); public static WebDriver getDriver() { if (driver.get() == null) { driver.set(new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), new ChromeOptions())); } return driver.get(); } ``` I suspect there might be a race condition or some scenario with session management in the Dockerized Selenium Grid. Has anyone else experienced this or can offer insight into how to handle WebDriver sessions more effectively in a remote setup? I appreciate any help or suggestions on debugging this scenario. I recently upgraded to Java LTS. I'd really appreciate any guidance on this. This is my first time working with Java 3.11. Is there a better approach? Has anyone else encountered this?