Java Code Examples for com.github.dockerjava.api.model.Ports#Binding

The following examples show how to use com.github.dockerjava.api.model.Ports#Binding . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ContainerState.java    From testcontainers-java with MIT License 6 votes vote down vote up
/**
 * Get the actual mapped port for a given port exposed by the container.
 * Should be used in conjunction with {@link #getHost()}.
 *
 * @param originalPort the original TCP port that is exposed
 * @return the port that the exposed port is mapped to, or null if it is not exposed
 */
default Integer getMappedPort(int originalPort) {
    Preconditions.checkState(this.getContainerId() != null, "Mapped port can only be obtained after the container is started");

    Ports.Binding[] binding = new Ports.Binding[0];
    final InspectContainerResponse containerInfo = this.getContainerInfo();
    if (containerInfo != null) {
        binding = containerInfo.getNetworkSettings().getPorts().getBindings().get(new ExposedPort(originalPort));
    }

    if (binding != null && binding.length > 0 && binding[0] != null) {
        return Integer.valueOf(binding[0].getHostPortSpec());
    } else {
        throw new IllegalArgumentException("Requested port (" + originalPort + ") is not mapped");
    }
}
 
Example 2
Source File: DockerComputerSSHConnector.java    From docker-plugin with MIT License 6 votes vote down vote up
private static InetSocketAddress getBindingForPort(DockerAPI api, InspectContainerResponse ir, int internalPort) {
    // get exposed port
    ExposedPort sshPort = new ExposedPort(internalPort);
    Integer port = 22;
    final NetworkSettings networkSettings = ir.getNetworkSettings();
    final Ports ports = networkSettings.getPorts();
    final Map<ExposedPort, Ports.Binding[]> bindings = ports.getBindings();
    // Get the binding that goes to the port that we're interested in (e.g: 22)
    final Ports.Binding[] sshBindings = bindings.get(sshPort);
    // Find where it's mapped to
    for (Ports.Binding b : sshBindings) {
        String hps = b.getHostPortSpec();
        port = Integer.valueOf(hps);
    }
    String host = getExternalIP(api, ir, networkSettings, sshBindings);
    return new InetSocketAddress(host, port);
}
 
Example 3
Source File: DockerComputerSSHConnectorTest.java    From docker-plugin with MIT License 6 votes vote down vote up
@Test
public void testPortBinding() throws IOException, InterruptedException {
    DockerComputerSSHConnector connector = new DockerComputerSSHConnector(Mockito.mock(DockerComputerSSHConnector.SSHKeyStrategy.class));
    CreateContainerCmdImpl cmd = new CreateContainerCmdImpl(Mockito.mock(CreateContainerCmd.Exec.class), Mockito.mock(AuthConfig.class), "");
    cmd.withPortBindings(PortBinding.parse("42:42"));

    connector.setPort(22);
    connector.beforeContainerCreated(Mockito.mock(DockerAPI.class), "/workdir", cmd);
    final Ports portBindings = cmd.getPortBindings();
    Assert.assertNotNull(portBindings);
    final Map<ExposedPort, Ports.Binding[]> bindingMap = portBindings.getBindings();
    Assert.assertNotNull(bindingMap);
    Assert.assertEquals(2, bindingMap.size());

    final Ports.Binding[] configuredBindings = bindingMap.get(new ExposedPort(42));
    Assert.assertNotNull(configuredBindings);
    Assert.assertEquals(1, configuredBindings.length);
    Assert.assertEquals("42", configuredBindings[0].getHostPortSpec());

    final Ports.Binding[] sshBindings = bindingMap.get(new ExposedPort(22));
    Assert.assertNotNull(sshBindings);
    Assert.assertEquals(1, sshBindings.length);
    Assert.assertNull(sshBindings[0].getHostPortSpec());

    System.out.println();
}
 
Example 4
Source File: ResultCallback.java    From Core with MIT License 5 votes vote down vote up
private Integer getPort(InspectContainerResponse info) {
    Map<ExposedPort, Ports.Binding[]> portBindings = info.getNetworkSettings().getPorts().getBindings();

    if (portBindings.keySet().size() > 0 && portBindings.keySet().iterator().next().getPort() != 0) {
        return portBindings.keySet().iterator().next().getPort();
    }

    return null;
}
 
Example 5
Source File: DefaultDockerClientIT.java    From junit5-docker with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("start a container with one port")
public void shouldStartContainerWithOnePort() {
    String containerId = defaultDockerClient.startContainer(WANTED_IMAGE, emptyMap(),
        new PortBinding(8081, 8080));
    InspectContainerResponse startedContainer = dockerClient.inspectContainerCmd(containerId).exec();
    Ports ports = startedContainer.getHostConfig().getPortBindings();
    assertThat(ports).isNotNull();
    Map<ExposedPort, Ports.Binding[]> portBindings = ports.getBindings();
    assertThat(portBindings).hasSize(1)
        .containsKeys(new ExposedPort(8080));
    assertThat(portBindings.get(new ExposedPort(8080))).hasSize(1)
        .extracting(Ports.Binding::getHostPortSpec)
        .contains("8081");
}
 
Example 6
Source File: ContainerState.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * @return the port bindings
 */
default List<String> getPortBindings() {
    List<String> portBindings = new ArrayList<>();
    final Ports hostPortBindings = this.getContainerInfo().getHostConfig().getPortBindings();
    for (Map.Entry<ExposedPort, Ports.Binding[]> binding : hostPortBindings.getBindings().entrySet()) {
        for (Ports.Binding portBinding : binding.getValue()) {
            portBindings.add(String.format("%s:%s", portBinding.toString(), binding.getKey()));
        }
    }
    return portBindings;
}
 
Example 7
Source File: DockerComputerSSHConnector.java    From docker-plugin with MIT License 5 votes vote down vote up
private static String getExternalIP(DockerAPI api, InspectContainerResponse ir, NetworkSettings networkSettings,
                             Ports.Binding[] sshBindings) {
    // If an explicit IP/hostname has been defined, always prefer this one
    String dockerHostname = api.getHostname();
    if (dockerHostname != null && !dockerHostname.trim().isEmpty()) {
        return dockerHostname;
    }
    // for (standalone) swarm, need to get the address of the actual host
    if (api.isSwarm()) {
        for (Ports.Binding b : sshBindings) {
            String ipAddress = b.getHostIp();
            if (ipAddress != null && !"0.0.0.0".equals(ipAddress)) {
                return ipAddress;
            }
        }
    }
    // see https://github.com/joyent/sdc-docker/issues/132
    final String driver = ir.getExecDriver();
    if (driver != null && driver.startsWith("sdc")) {
        // We run on Joyent's Triton
        // see https://docs.joyent.com/public-cloud/instances/docker/how/inspect-containers
        return networkSettings.getIpAddress();
    }
    final URI uri = URI.create(api.getDockerHost().getUri());
    if(uri.getScheme().equals("unix")) {
        // Communicating with unix domain socket. so we assume localhost
        return "0.0.0.0";
    }
    return uri.getHost();
}
 
Example 8
Source File: SwarmCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
private DockerClient initializeDockerClient(Ports.Binding binding) {
    DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
        .withRegistryUrl("https://index.docker.io/v1/")
        .withDockerHost("tcp://" + binding).build();
    return getFactoryType().createDockerClient(config);
}