Search code examples
dockerdocker-java

How To Create And Start Docker Container with specific port, detached mode using docker-java


I want to create and run docker using docker java client. I want running something like this :

docker run -d -p 4444:4444 --name selenium-hub selenium/hub:2.53.0

How to implement this command on docker-java client? Here is my code so far :

CreateContainerResponse response = dockerClient.createContainerCmd("selenium/hub")
               .withName(name)
               .exec();

Actually IDK how to specify -d (for running in background). and -p. please help me. sorry I am new in Docker.


Solution

  • Found the solution... if someone find a better one please post in here. I already modify the code to be like this :

      ExposedPort tcp4444 = ExposedPort.tcp(4444);
       Ports portBindings = new Ports();
       portBindings.bind(tcp4444,Ports.Binding.bindPort(4444));
    
       CreateContainerResponse response = dockerClient.
               createContainerCmd("selenium/hub")
               .withName(name)
               .withImage("selenium/hub:"+version)
               .withExposedPorts(tcp4444)
               .withPortBindings(portBindings)
               .withAttachStderr(false)
               .withAttachStdin(false)
               .withAttachStdout(false)
               .exec();`