Hello, today, I am going to tell you how you can manage your Docker-based Selenium Grid containers via Java code. The main reason behind it is the need of Selenium Grid for parallel execution. In our pipeline, there’s already a Selenoid and Selenoid-UI image working but for local issues, we don’t want to keep production busy. So we created a small java class to create a local hub.

Here’s what our class does.

  • First,  we check if the container is up and running. We do this by running the “docker inspect -f {{.State.Running}} CONTAINERID” command. This command returns as true or false as a response. This is done by the checkAlive(String containerId) method.
  • Then if the state is false, we run “docker run CONTAINERID” command to run our containers. This is done by startDocker(“”) method.
  • There’s also a method to stop the docker container. This runs “docker stop CONTAINERID”

We also have some helper methods that parse the result of command-line interfaces. The reason is that when you run some commands with the Runtime object, you need the response to understand the response.

Those are the main functions that we use in our BaseTest.

As the methods are parameterized, you can run any Docker image without having any problem.

Whole Source Code

Note: Also, we can use external libraries which wrap docker commands for us. For e.g., we could make use of Testcontainers to basically control the starting and stopping of a selenium grid. https://www.testcontainers.org A sample from their site that shows how to use the test containers: https://github.com/testcontainers/testcontainers-java-examples/blob/master/selenium-container/src/test/java/SeleniumContainerTest.java  As we can see from this, the test containers library abstracts out a lot of stuff for us and makes it easy to work with containers for our tests. Thanks to Krishan Mahadevan for his valuable feedback.

Thanks.
Canberk Akduygu