如何创build和启动Docker容器与特定的端口,使用docker-java分离模式

我想使用docker java客户端来创build和运行docker。 我想运行这样的东西:

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

如何在docker-java客户端上实现这个命令? 这是我的代码到目前为止:

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

其实IDK如何指定-d(在后台运行)。 和-p。 请帮帮我。 抱歉,我是Docker中的新成员。

docker-java在https://github.com/docker-java/docker-java/wiki上有一个很好的wiki。 search“端口”让我这个:

创build新的Docker容器并使用暴露的端口启动它

 ExposedPort tcp22 = ExposedPort.tcp(22); ExposedPort tcp23 = ExposedPort.tcp(23); Ports portBindings = new Ports(); portBindings.bind(tcp22, Ports.Binding(11022)); portBindings.bind(tcp23, Ports.Binding(11023)); CreateContainerResponse container = dockerClient.createContainerCmd("busybox") .withCmd("true") .withExposedPorts(tcp22, tcp23) .withPortBindings(portBindings) .exec(); 

我看了一下Docker-java中的一些testing,看起来你只做了一半的工作来运行一个容器,因为你只创build了容器,并没有启动它。 根据我在这个testing中看到的( https://github.com/docker-java/docker-java/blob/069987852c842e3bba85ed3325a8877c36f9e87f/src/test/java/com/github/dockerjava/core/command/ExecStartCmdImplTest.java#L69 ),你的代码应该看起来像这样:

 ExposedPort tcp4444 = ExposedPort.tcp(4444); Ports portBindings = new Ports(); portBindings.bind(tcp4444, Ports.Binding(4444)); // Create the container (it will not be running) CreateContainerResponse container = dockerClient.createContainerCmd("selenium/hub") .withName(name) .withExposedPorts(tcp4444) .withPortBindings(portBindings) .exec(); // Actually run the container dockerClient.startContainerCmd(container).exec(); 

据我所知,没有理由显式运行它在分离模式,因为它将被默认启动asynchronous。

find解决scheme…如果有人find一个更好的一个请在这里张贴。 我已经修改代码是这样的:

  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();`