Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for custom port bindings #13

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 14 additions & 7 deletions src/main/java/com/github/geowarin/junit/DockerRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,7 @@
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.*;

import static com.spotify.docker.client.DockerClient.LogsParam.follow;
import static com.spotify.docker.client.DockerClient.LogsParam.stdout;
Expand Down Expand Up @@ -134,9 +131,19 @@ protected DockerClient createDockerClient() {

protected ContainerConfig createContainerConfig(String imageName, String[] ports, String cmd) {
Map<String, List<PortBinding>> portBindings = new HashMap<>();
List<String> exposedPorts = new ArrayList<>();

for (String port : ports) {
List<PortBinding> hostPorts = Collections.singletonList(PortBinding.randomPort("0.0.0.0"));
portBindings.put(port, hostPorts);
if (port.contains(":")) {
String[] splitPorts = port.split(":");
List<PortBinding> hostPorts = Collections.singletonList(PortBinding.of("0.0.0.0", splitPorts[1]));
portBindings.put(splitPorts[0], hostPorts);
exposedPorts.add(splitPorts[0]);
} else {
List<PortBinding> hostPorts = Collections.singletonList(PortBinding.randomPort("0.0.0.0"));
portBindings.put(port, hostPorts);
exposedPorts.add(port);
}
}

HostConfig hostConfig = HostConfig.builder()
Expand All @@ -147,7 +154,7 @@ protected ContainerConfig createContainerConfig(String imageName, String[] ports
.hostConfig(hostConfig)
.image(imageName)
.networkDisabled(false)
.exposedPorts(ports);
.exposedPorts(exposedPorts.toArray(new String[0]));

if (cmd != null) {
configBuilder = configBuilder.cmd(cmd);
Expand Down
2 changes: 1 addition & 1 deletion src/test/java/integration/RabbitIntegrationTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public class RabbitIntegrationTest {
public static DockerRule rabbitRule =
DockerRule.builder()
.image("rabbitmq:management")
.ports("5672")
.ports("5672:5672")
// .waitForPort("5672/tcp")
.waitForLog("Server startup complete")
.build();
Expand Down