com.github.dockerjava.api.model.PortBinding Java Examples

The following examples show how to use com.github.dockerjava.api.model.PortBinding. 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: 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 #2
Source File: DockerComputerSSHConnector.java    From docker-plugin with MIT License 6 votes vote down vote up
@Override
public void beforeContainerCreated(DockerAPI api, String workdir, CreateContainerCmd cmd) throws IOException, InterruptedException {
    // TODO define a strategy for SSHD process configuration so we support more than openssh's sshd
    final String[] cmdArray = cmd.getCmd();
    if (cmdArray == null || cmdArray.length == 0) {
        if (sshKeyStrategy.getInjectedKey() != null) {
            cmd.withCmd("/usr/sbin/sshd", "-D", "-p", String.valueOf(port),
                    // override sshd_config to force retrieval of InstanceIdentity public for as authentication
                    "-o", "AuthorizedKeysCommand=/root/authorized_key",
                    "-o", "AuthorizedKeysCommandUser=root"
            );
        } else {
            cmd.withCmd("/usr/sbin/sshd", "-D", "-p", String.valueOf(port));
        }
    }
    cmd.withPortSpecs(port+"/tcp");
    final PortBinding sshPortBinding = PortBinding.parse(":" + port);
    final Ports portBindings = cmd.getPortBindings();
    if(portBindings != null) {
        portBindings.add(sshPortBinding);
        cmd.withPortBindings(portBindings);
    } else {
        cmd.withPortBindings(sshPortBinding);
    }
    cmd.withExposedPorts(ExposedPort.parse(port+"/tcp"));
}
 
Example #3
Source File: DockerTemplateBase.java    From docker-plugin with MIT License 6 votes vote down vote up
@Nonnull
public Iterable<PortBinding> getPortMappings() {
    if (Strings.isNullOrEmpty(bindPorts)) {
        return Collections.emptyList();
    }
    return Iterables.transform(Splitter.on(' ')
                    .trimResults()
                    .omitEmptyStrings()
                    .split(bindPorts),
            new Function<String, PortBinding>() {
                @Nullable
                @Override
                public PortBinding apply(String s) {
                    return PortBinding.parse(s);
                }
            });
}
 
Example #4
Source File: SyndesisIntegrationRuntimeContainer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public SyndesisIntegrationRuntimeContainer build() {
    CustomizedIntegrationSource source = new CustomizedIntegrationSource(integrationSource, customizers);
    Project project = getProjectBuilder().build(source);

    SyndesisIntegrationRuntimeContainer container = getContainer(project);

    if (enableLogging) {
        container.withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("INTEGRATION_RUNTIME_CONTAINER")));
    }

    if (enableDebug) {
        container.withExposedPorts(SyndesisTestEnvironment.getDebugPort());
        container.withCreateContainerCmdModifier(cmd -> cmd.withPortBindings(new PortBinding(Ports.Binding.bindPort(SyndesisTestEnvironment.getDebugPort()),
                new ExposedPort(SyndesisTestEnvironment.getDebugPort()))));
    }

    container.waitingFor(SyndesisTestEnvironment.getIntegrationRuntime().getReadinessProbe().withStartupTimeout(startupTimeout));

    return container;
}
 
Example #5
Source File: SyndesisServerContainer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public SyndesisServerContainer build() {
    SyndesisServerContainer container;
    if (ObjectHelper.isEmpty(serverJarPath)) {
        container = new SyndesisServerContainer(serverJarPath, getJavaOptionString(), deleteOnExit);
    } else {
        container = new SyndesisServerContainer(imageTag, getJavaOptionString());
    }

    if (enableLogging) {
        container.withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("SERVER_CONTAINER")));
    }

    container.withCreateContainerCmdModifier(createContainerCmd -> createContainerCmd.withName("syndesis-server"));

    if (enableDebug) {
        container.withExposedPorts(SERVER_PORT, JOLOKIA_PORT, SyndesisTestEnvironment.getDebugPort());
        container.withCreateContainerCmdModifier(cmd -> cmd.withPortBindings(new PortBinding(Ports.Binding.bindPort(SyndesisTestEnvironment.getDebugPort()), new ExposedPort(SyndesisTestEnvironment.getDebugPort()))));
    } else {
        container.withExposedPorts(SERVER_PORT, JOLOKIA_PORT);
    }

    container.waitingFor(new HttpWaitStrategy().forPort(SERVER_PORT)
                                               .withStartupTimeout(Duration.ofMinutes(3)));

    return container;
}
 
Example #6
Source File: ContainersProvider.java    From replicator with Apache License 2.0 6 votes vote down vote up
private GenericContainer<?> getContainer(String image, int port, Network network, String logWaitRegex, int logWaitTimes, boolean matchExposedPort) {

        GenericContainer<?> container = new GenericContainer<>(image)
                .withExposedPorts(port)
                .waitingFor(
                        Wait.forLogMessage(logWaitRegex, logWaitTimes).withStartupTimeout(Duration.ofMinutes(5L))
                );

        if (network != null) {
            container.withNetwork(network);
        }

        if (matchExposedPort) {
            container.withCreateContainerCmdModifier(
                    command -> command.withPortBindings(PortBinding.parse(String.format("%d:%d", port, port)))
            );
        }

        container.withLogConsumer(outputFrame -> {
//            System.out.println(image + " " + outputFrame.getUtf8String());
        });


        return container;
    }
 
Example #7
Source File: DockerBridgeTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithAContainerWithAPort() throws InterruptedException {
  CreateContainerResponse container = client.createContainerCmd("nginx")
      .withExposedPorts(ExposedPort.tcp(80), ExposedPort.tcp(443))
      .withPortBindings(PortBinding.parse("80"))
      .exec();

  AtomicBoolean done = new AtomicBoolean();
  Promise<Void> promise = Promise.promise();
  promise.future().onComplete(ar -> done.set(ar.succeeded()));
  bridge.scan(promise);
  await().untilAtomic(done, is(true));
  assertThat(bridge.getServices()).hasSize(0);

  done.set(false);
  client.startContainerCmd(container.getId()).exec();
  Promise<Void> promise2 = Promise.promise();
  promise2.future().onComplete(ar -> done.set(ar.succeeded()));
  bridge.scan(promise2);
  await().untilAtomic(done, is(true));

  assertThat(bridge.getServices()).hasSize(1);
  DockerService service = bridge.getServices().get(0);
  assertThat(service.records()).hasSize(1);
}
 
Example #8
Source File: DockerBridgeTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithAContainerWithLabels() throws InterruptedException {
  Map<String, String> labels = new LinkedHashMap<>();
  labels.put("service.type", "http-endpoint");
  labels.put("ssl", "true");
  CreateContainerResponse container = client.createContainerCmd("nginx")
      .withExposedPorts(ExposedPort.tcp(80), ExposedPort.tcp(443))
      .withPortBindings(PortBinding.parse("80"))
      .withLabels(labels)
      .exec();

  AtomicBoolean done = new AtomicBoolean();
  Promise<Void> promise = Promise.promise();
  promise.future().onComplete(ar -> done.set(ar.succeeded()));
  bridge.scan(promise);
  await().untilAtomic(done, is(true));
  assertThat(bridge.getServices()).hasSize(0);

  done.set(false);
  client.startContainerCmd(container.getId()).exec();
  Promise<Void> promise2 = Promise.promise();
  promise2.future().onComplete(ar -> done.set(ar.succeeded()));
  bridge.scan(promise2);
  await().untilAtomic(done, is(true));

  assertThat(bridge.getServices()).hasSize(1);
  DockerService service = bridge.getServices().get(0);
  assertThat(service.records()).hasSize(1);
  assertThat(service.records().get(0).getLocation().getString("endpoint")).startsWith("https");
}
 
Example #9
Source File: ContainerLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCreatingContainer_thenMustReturnContainerId() {

    // when
    CreateContainerResponse container = dockerClient.createContainerCmd("mongo:3.6").withCmd("--bind_ip_all").withName("mongo").withHostName("baeldung").withEnv("MONGO_LATEST_VERSION=3.6").withPortBindings(PortBinding.parse("9999:27017")).exec();

    // then
    MatcherAssert.assertThat(container.getId(), is(not(null)));
}
 
Example #10
Source File: CreateContainerCmd.java    From docker-java with Apache License 2.0 5 votes vote down vote up
/**
 * Add one or more {@link PortBinding}s. This corresponds to the <code>--publish</code> (<code>-p</code>) option of the
 * <code>docker run</code> CLI command.
 *
 * @deprecated see {@link #getHostConfig()}
 */
@Deprecated
default CreateContainerCmd withPortBindings(PortBinding... portBindings) {
    Objects.requireNonNull(portBindings, "portBindings was not specified");
    getHostConfig().withPortBindings(new Ports(portBindings));
    return this;
}
 
Example #11
Source File: ContainerState.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * @return the bound port numbers
 */
default List<Integer> getBoundPortNumbers() {
    return getPortBindings().stream()
        .map(PortBinding::parse)
        .map(PortBinding::getBinding)
        .map(Ports.Binding::getHostPortSpec)
        .filter(Objects::nonNull)
        .map(Integer::valueOf)
        .collect(Collectors.toList());
}
 
Example #12
Source File: GenericContainer.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * @return the port on which to check if the container is ready
 * @deprecated see {@link GenericContainer#getLivenessCheckPorts()} for replacement
 */
@Deprecated
protected Integer getLivenessCheckPort() {
    // legacy implementation for backwards compatibility
    Iterator<Integer> exposedPortsIterator = exposedPorts.iterator();
    if (exposedPortsIterator.hasNext()) {
        return getMappedPort(exposedPortsIterator.next());
    } else if (portBindings.size() > 0) {
        return Integer.valueOf(PortBinding.parse(portBindings.get(0)).getBinding().getHostPortSpec());
    } else {
        return null;
    }
}
 
Example #13
Source File: DockerBridgeTest.java    From vertx-service-discovery with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithAContainerWithTwoPorts() throws InterruptedException {
  CreateContainerResponse container = client.createContainerCmd("nginx")
      .withExposedPorts(ExposedPort.tcp(80), ExposedPort.tcp(443))
      .withPortBindings(PortBinding.parse("80"), PortBinding.parse("443"))
      .exec();

  AtomicBoolean done = new AtomicBoolean();
  Promise<Void> promise = Promise.promise();
  promise.future().onComplete(ar -> done.set(ar.succeeded()));
  bridge.scan(promise);
  await().untilAtomic(done, is(true));
  assertThat(bridge.getServices()).hasSize(0);

  done.set(false);
  client.startContainerCmd(container.getId()).exec();
  Promise<Void> promise2 = Promise.promise();
  promise2.future().onComplete(ar -> done.set(ar.succeeded()));
  bridge.scan(promise2);
  await().untilAtomic(done, is(true));

  assertThat(bridge.getServices()).hasSize(1);
  DockerService service = bridge.getServices().get(0);
  assertThat(service.records()).hasSize(2);

  client.stopContainerCmd(container.getId()).exec();


  done.set(false);
  Promise<Void> promise3 = Promise.promise();
  promise3.future().onComplete(ar -> done.set(ar.succeeded()));
  bridge.scan(promise3);
  await().untilAtomic(done, is(true));
  assertThat(bridge.getServices()).hasSize(0);

}
 
Example #14
Source File: SyndesisDbContainer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public SyndesisDbContainer() {
    withDatabaseName("sampledb");
    withUsername("sampledb");
    withPassword("secret");

    withCreateContainerCmdModifier(cmd -> cmd.withName("syndesis-db"));
    withCreateContainerCmdModifier(cmd -> cmd.withPortBindings(new PortBinding(Ports.Binding.bindPort(DB_PORT), new ExposedPort(DB_PORT))));
    withInitScript("syndesis-db-init.sql");

    withNetwork(Network.newNetwork());
    withNetworkAliases("syndesis-db");
}
 
Example #15
Source File: DockerTestUtils.java    From module-ballerina-docker with Apache License 2.0 5 votes vote down vote up
/**
 * Create port mapping from host to docker instance.
 *
 * @param dockerPortBindings Ports needed exposed. Key is docker instance port and value is host port.
 * @return The configuration.
 */
private static HostConfig getPortMappingForHost(List<Integer> dockerPortBindings) {
    List<PortBinding> portBindings = new ArrayList<>();

    for (Integer dockerPortBinding : dockerPortBindings) {
        PortBinding portBinding = new PortBinding(
                Ports.Binding.bindIpAndPort("0.0.0.0", Integer.parseInt(dockerPortBinding.toString())),
                ExposedPort.parse(dockerPortBinding.toString()));
        portBindings.add(portBinding);
    }

    return HostConfig.newHostConfig().withPortBindings(portBindings);
}
 
Example #16
Source File: BesuNode.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
private PortBinding httpRpcPortBinding() {
  return new PortBinding(new Binding(null, null), ExposedPort.tcp(DEFAULT_HTTP_RPC_PORT));
}
 
Example #17
Source File: PrivateRegistryRule.java    From docker-java with Apache License 2.0 4 votes vote down vote up
/**
 * Starts a local test registry when it is not already started and returns the auth configuration for it
 * This method is synchronized so that only the first invocation starts the registry
 */
@Override
protected void before() throws Throwable {

    int port = 5050;

    String imageName = "private-registry-image";

    File baseDir = new File(DockerRule.class.getResource("/privateRegistry").getFile());

    String registryImageId = dockerClient.buildImageCmd(baseDir)
            .withNoCache(true)
            .start()
            .awaitImageId();

    InspectImageResponse inspectImageResponse = dockerClient.inspectImageCmd(registryImageId).exec();
    assertThat(inspectImageResponse, not(nullValue()));
    DockerRule.LOG.info("Image Inspect: {}", inspectImageResponse.toString());

    dockerClient.tagImageCmd(registryImageId, imageName, "2")
            .withForce().exec();

    // see https://github.com/docker/distribution/blob/master/docs/deploying.md#native-basic-auth
    CreateContainerResponse testregistry = dockerClient
            .createContainerCmd(imageName + ":2")
            .withHostConfig(newHostConfig()
                    .withPortBindings(new PortBinding(Ports.Binding.bindPort(port), ExposedPort.tcp(5000))))
            .withEnv("REGISTRY_AUTH=htpasswd", "REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm",
                    "REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd", "REGISTRY_LOG_LEVEL=debug",
                    "REGISTRY_HTTP_TLS_CERTIFICATE=/certs/domain.crt", "REGISTRY_HTTP_TLS_KEY=/certs/domain.key")
            .exec();

    containerId = testregistry.getId();
    dockerClient.startContainerCmd(containerId).exec();

    // wait for registry to boot
    Thread.sleep(3000);

    // credentials as configured in /auth/htpasswd
    authConfig = new AuthConfig()
            .withUsername("testuser")
            .withPassword("testpassword")
            .withRegistryAddress("localhost:" + port);
}
 
Example #18
Source File: DockerTemplate.java    From docker-plugin with MIT License 4 votes vote down vote up
public Iterable<PortBinding> getPortMappings() {
    return dockerTemplateBase.getPortMappings();
}
 
Example #19
Source File: CreateContainerWorkitemHandler.java    From jbpm-work-items with Apache License 2.0 4 votes vote down vote up
public void executeWorkItem(WorkItem workItem,
                            WorkItemManager workItemManager) {

    Map<String, Object> results = new HashMap<String, Object>();

    try {

        RequiredParameterValidator.validate(this.getClass(),
                                            workItem);

        String containerName = (String) workItem.getParameter("ContainerName");
        String containerImageName = (String) workItem.getParameter("ContainerImageName");
        String containerCommand = (String) workItem.getParameter("ContainerCommand");
        String containerHostName = (String) workItem.getParameter("ContainerHostName");
        String containerEnv = (String) workItem.getParameter("ContainerEnv");
        String containerPortBindings = (String) workItem.getParameter("ContainerPortBindings");
        String containerBinds = (String) workItem.getParameter("ContainerBinds");

        if (dockerClient == null) {
            DockerClientConnector connector = new DockerClientConnector();
            dockerClient = connector.getDockerClient();
        }

        CreateContainerCmd createContainerCmd = dockerClient.createContainerCmd(containerImageName).withName(containerName);

        if (containerCommand != null) {
            createContainerCmd = createContainerCmd.withCmd(containerCommand);
        }

        if (containerHostName != null) {
            createContainerCmd = createContainerCmd.withHostName(containerHostName);
        }

        if (containerEnv != null) {
            createContainerCmd = createContainerCmd.withEnv(containerEnv);
        }

        if (containerPortBindings != null) {
            createContainerCmd = createContainerCmd.withPortBindings(PortBinding.parse(containerPortBindings));
        }

        if (containerBinds != null) {
            createContainerCmd = createContainerCmd.withBinds(Bind.parse(containerBinds));
        }

        CreateContainerResponse container = createContainerCmd.exec();

        if (container != null && container.getId() != null) {
            results.put(RESULTS_DOCUMENT,
                        container.getId());
        }

        workItemManager.completeWorkItem(workItem.getId(),
                                         results);
    } catch (Exception e) {
        logger.error("Unable to create container: " + e.getMessage());
        handleException(e);
    }
}
 
Example #20
Source File: KafkaConnectConverterIT.java    From apicurio-registry with Apache License 2.0 4 votes vote down vote up
@BeforeEach
public void startContainers() {
    String apicurioVersion = System.getProperty("project.version");
    assertNotNull(apicurioVersion);

    Path converterDistro = Paths.get(System.getProperty("user.dir"), "..", "distro", "connect-converter",
            "target", "apicurio-kafka-connect-converter-" + apicurioVersion + "-converter.tar.gz");

    if (Files.notExists(converterDistro)) {
        LOGGER.info("Connecter distribution {}", converterDistro.toString());
        throw new IllegalStateException("Kafka connect converter distribution is not present");
    }

    ImageFromDockerfile apicurioDebeziumImage = new ImageFromDockerfile()
            .withFileFromPath("converter-distro.tar.gz", converterDistro)
            .withDockerfileFromBuilder(builder -> builder
                    .from("debezium/connect:1.1.1.Final")
                    .env("KAFKA_CONNECT_DEBEZIUM_DIR", "$KAFKA_CONNECT_PLUGINS_DIR/debezium-connector-postgres")
                    .copy("converter-distro.tar.gz", "$KAFKA_CONNECT_DEBEZIUM_DIR/apicurio-kafka-connect-converter.tar.gz")
                    .run("cd $KAFKA_CONNECT_DEBEZIUM_DIR && tar -xvf apicurio-kafka-connect-converter.tar.gz")
                    .build());

    if (!TestUtils.isExternalRegistry()) {
        Testcontainers.exposeHostPorts(8081);
    }

    Testcontainers.exposeHostPorts(9092);
    kafka = new KafkaContainer();
    kafka.addEnv("KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR", "1");
    kafka.addEnv("KAFKA_TRANSACTION_STATE_LOG_MIN_ISR", "1");
    kafka.addExposedPorts(9092);
    kafka.withCreateContainerCmdModifier(cmd -> {
        cmd
                .withHostName("localhost")
                .withPortBindings(new PortBinding(Ports.Binding.bindPort(9092), new ExposedPort(9092)));
    });
    kafka.start();

    Network network = Network.newNetwork();

    postgres = new PostgreSQLContainer<>("debezium/postgres:11")
          .withNetwork(network)
          .withNetworkAliases("postgres");
    postgres.start();

    debeziumContainer = new DebeziumContainer("dummy-version");
    debeziumContainer.setImage(apicurioDebeziumImage);
    debeziumContainer.withNetwork(network)
          .withEnv("BOOTSTRAP_SERVERS", "host.testcontainers.internal:9092")
          .withLogConsumer(new Slf4jLogConsumer(LOGGER));
    debeziumContainer.setWaitStrategy(
            Wait.forHttp("/connectors")
            .forPort(8083)
            .forStatusCode(200)
            .withReadTimeout(Duration.ofSeconds(3))
            .withStartupTimeout(Duration.ofSeconds(300)));
    debeziumContainer.start();

}
 
Example #21
Source File: BesuNode.java    From ethsigner with Apache License 2.0 4 votes vote down vote up
private PortBinding wsRpcPortBinding() {
  return new PortBinding(new Binding(null, null), ExposedPort.tcp(DEFAULT_WS_RPC_PORT));
}
 
Example #22
Source File: CreateContainerCmd.java    From docker-java with Apache License 2.0 2 votes vote down vote up
/**
 * Add one or more {@link PortBinding}s. This corresponds to the <code>--publish</code> (<code>-p</code>) option of the
 * <code>docker run</code> CLI command.
 *
 * @deprecated see {@link #getHostConfig()}
 */
@Deprecated
default CreateContainerCmd withPortBindings(List<PortBinding> portBindings) {
    Objects.requireNonNull(portBindings, "portBindings was not specified");
    return withPortBindings(portBindings.toArray(new PortBinding[0]));
}