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

The following examples show how to use com.github.dockerjava.api.model.ContainerNetwork. 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: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void createContainerWithNetworkID() {
    assumeThat("API version should be >= 1.23", dockerRule, isGreaterOrEqual(VERSION_1_24));

    String networkName = "net-" + UUID.randomUUID().toString();
    Map<String, String> labels = new HashMap<>();
    labels.put("com.example.label", "test");
    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd().withName(networkName)
            .withLabels(labels).withAttachable(true).exec();
    String networkId = createNetworkResponse.getId();
    CreateContainerResponse createContainerResponse = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE).withLabels(labels).withCmd("true").exec();
    String containerId = createContainerResponse.getId();
    dockerRule.getClient().connectToNetworkCmd().withContainerId(containerId).withNetworkId(networkId).exec();
    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(containerId).exec();
    ContainerNetwork containerNetwork = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkName);
    if (containerNetwork == null) {
        // swarm node used network id
        containerNetwork = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkId);
    }
    assertThat(containerNetwork, notNullValue());
}
 
Example #2
Source File: DockerUtils.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static String getContainerIP(DockerClient docker, String containerId) {
    for (Map.Entry<String, ContainerNetwork> e : docker.inspectContainerCmd(containerId)
             .exec().getNetworkSettings().getNetworks().entrySet()) {
        return e.getValue().getIpAddress();
    }
    throw new IllegalArgumentException("Container " + containerId + " has no networks");
}
 
Example #3
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createContainerWithAlias() throws DockerException {
    String containerName1 = "containerAlias_" + dockerRule.getKind();
    String networkName = "aliasNet" + dockerRule.getKind();

    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd()
            .withName(networkName)
            .withDriver("bridge")
            .exec();

    assertNotNull(createNetworkResponse.getId());

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withHostConfig(newHostConfig()
                    .withNetworkMode(networkName))
            .withCmd("sleep", "9999")
            .withName(containerName1)
            .withAliases("server" + dockerRule.getKind())
            .exec();

    assertThat(container.getId(), not(is(emptyString())));

    dockerRule.getClient().startContainerCmd(container.getId()).exec();

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId())
            .exec();

    ContainerNetwork aliasNet = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkName);
    assertThat(aliasNet.getAliases(), hasItem("server" + dockerRule.getKind()));
}
 
Example #4
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createContainerWithCustomIp() throws DockerException {
    String containerName1 = "containerCustomIplink_" + dockerRule.getKind();
    String networkName = "customIpNet" + dockerRule.getKind();
    String subnetPrefix = getFactoryType().getSubnetPrefix() + "101";

    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd()
            .withIpam(new Network.Ipam()
                    .withConfig(new Network.Ipam.Config()
                            .withSubnet(subnetPrefix + ".0/24")))
            .withDriver("bridge")
            .withName(networkName)
            .exec();

    assertNotNull(createNetworkResponse.getId());

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withHostConfig(newHostConfig()
                    .withNetworkMode(networkName))
            .withCmd("sleep", "9999")
            .withName(containerName1)
            .withIpv4Address(subnetPrefix + ".100")
            .exec();

    assertThat(container.getId(), not(is(emptyString())));

    dockerRule.getClient().startContainerCmd(container.getId()).exec();

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient()
            .inspectContainerCmd(container.getId())
            .exec();

    ContainerNetwork customIpNet = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkName);
    assertNotNull(customIpNet);
    assertThat(customIpNet.getGateway(), is(subnetPrefix + ".1"));
    assertThat(customIpNet.getIpAddress(), is(subnetPrefix + ".100"));
}
 
Example #5
Source File: Docker.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public Map<String, ContainerNetwork> getContainerNetworks() {
    if (isRunningInContainer()) {
        Map<String, ContainerNetwork> networks = inspectContainer(getContainerName()).getNetworkSettings()
            .getNetworks();
        log.trace("Docker container networks {}", networks);
        return networks;
    } else {
        throw new DockerClientException(
            "Can't obtain container ip address if not running in container");
    }
}
 
Example #6
Source File: Docker.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
private void logNetworks(String containerId) {
    Map<String, ContainerNetwork> networks = getClient().inspectContainerCmd(containerId).exec().getNetworkSettings().getNetworks();
    int networksSize = networks.size();
    log.debug("There are {} network(s) in the container {}", networksSize, containerId);
    if (networksSize == 0) {
        return;
    }
    int i = 0;
    for (Entry<String, ContainerNetwork> network : networks.entrySet()) {
        log.debug("{}) {} -> {}", ++i, network.getKey(), network.getValue());
    }
}
 
Example #7
Source File: DockerContainer.java    From james-project with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public String getContainerIp() {
    return container.getContainerInfo()
        .getNetworkSettings()
        .getNetworks()
        .values()
        .stream()
        .map(ContainerNetwork::getIpAddress)
        .findFirst()
        .orElseThrow(IllegalStateException::new);
}
 
Example #8
Source File: GenericContainer.java    From testcontainers-java with MIT License 5 votes vote down vote up
private void connectToPortForwardingNetwork(String networkMode) {
    PortForwardingContainer.INSTANCE.getNetwork().map(ContainerNetwork::getNetworkID).ifPresent(networkId -> {
        if (!Arrays.asList(networkId, "none", "host").contains(networkMode)) {
            dockerClient.connectToNetworkCmd().withContainerId(containerId).withNetworkId(networkId).exec();
        }
    });
}
 
Example #9
Source File: CouchbaseContainer.java    From testcontainers-java with MIT License 5 votes vote down vote up
/**
 * Helper method to extract the internal IP address based on the network configuration.
 */
private String getInternalIpAddress() {
    return getContainerInfo().getNetworkSettings().getNetworks().values().stream()
        .findFirst()
        .map(ContainerNetwork::getIpAddress)
        .orElseThrow(() -> new IllegalStateException("No network available to extract the internal IP from!"));
}
 
Example #10
Source File: InspectContainerResponseTest.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void inspect_windows_container() throws IOException {

    final JavaType type = JSONTestHelper.getMapper().getTypeFactory().constructType(InspectContainerResponse.class);

    final InspectContainerResponse response = testRoundTrip(RemoteApiVersion.VERSION_1_38,
        "/containers/inspect/lcow.json",
        type
    );

    assertThat(response, notNullValue());

    assertThat(response.getConfig(), notNullValue());
    assertThat(response.getConfig().getCmd(), is(new String[]{"cmd"}));
    assertThat(response.getConfig().getImage(), is("microsoft/nanoserver"));

    assertThat(response.getDriver(), is("windowsfilter"));

    assertThat(response.getGraphDriver(), notNullValue());
    assertThat(response.getGraphDriver().getName(), is("windowsfilter"));
    assertThat(response.getGraphDriver().getData(), is(new GraphData().withDir(
        "C:\\ProgramData\\Docker\\windowsfilter\\35da02ca897bd378ee52be3066c847fee396ba1a28a00b4be36f42c6686bf556"
    )));

    assertThat(response.getHostConfig(), notNullValue());
    assertThat(response.getHostConfig().getIsolation(), is(Isolation.HYPERV));

    assertThat(response.getImageId(), is("sha256:1381511ec0122f197b6abff5bc0692bef19943ddafd6680eff41197afa3a6dda"));
    assertThat(response.getLogPath(), is(
        "C:\\ProgramData\\Docker\\containers\\35da02ca897bd378ee52be3066c847fee396ba1a28a00b4be36f42c6686bf556" +
            "\\35da02ca897bd378ee52be3066c847fee396ba1a28a00b4be36f42c6686bf556-json.log"
    ));
    assertThat(response.getName(), is("/cranky_clarke"));

    assertThat(response.getNetworkSettings(), notNullValue());
    assertThat(response.getNetworkSettings().getNetworks(), is(Collections.singletonMap("nat",
        new ContainerNetwork()
            .withEndpointId("493b77d6fe7e3b92435b1eb01461fde669781330deb84a9cbada360db8997ebc")
            .withGateway("172.17.18.1")
            .withGlobalIPv6Address("")
            .withGlobalIPv6PrefixLen(0)
            .withIpv4Address("172.17.18.123")
            .withIpPrefixLen(16)
            .withIpV6Gateway("")
            .withMacAddress("00:aa:ff:cf:dd:09")
            .withNetworkID("398c0e206dd677ed4a6566f9de458311f5767d8c7a8b963275490ab64c5d10a7")
    )));

    assertThat(response.getPath(), is("cmd"));
    assertThat(response.getPlatform(), is("windows"));
}
 
Example #11
Source File: CreateContainerCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void createContainerWithLinkInCustomNetwork() throws DockerException {
    String containerName1 = "containerCustomlink_" + dockerRule.getKind();
    String containerName2 = "containerCustom2link_" + dockerRule.getKind();
    String networkName = "linkNetcustom" + dockerRule.getKind();

    CreateNetworkResponse createNetworkResponse = dockerRule.getClient().createNetworkCmd()
            .withName(networkName)
            .withDriver("bridge")
            .exec();

    assertNotNull(createNetworkResponse.getId());

    CreateContainerResponse container1 = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withHostConfig(newHostConfig()
                    .withNetworkMode(networkName))
            .withCmd("sleep", "9999")
            .withName(containerName1)
            .exec();

    assertThat(container1.getId(), not(is(emptyString())));

    dockerRule.getClient().startContainerCmd(container1.getId()).exec();

    InspectContainerResponse inspectContainerResponse1 = dockerRule.getClient().inspectContainerCmd(container1.getId())
            .exec();
    LOG.info("Container1 Inspect: {}", inspectContainerResponse1.toString());
    assertThat(inspectContainerResponse1.getState().getRunning(), is(true));

    CreateContainerResponse container2 = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
            .withHostConfig(newHostConfig()
                    .withLinks(new Link(containerName1, containerName1 + "Link"))
                    .withNetworkMode(networkName))
            .withName(containerName2)
            .withCmd("env")
            .exec();

    LOG.info("Created container {}", container2.toString());
    assertThat(container2.getId(), not(is(emptyString())));

    InspectContainerResponse inspectContainerResponse2 = dockerRule.getClient().inspectContainerCmd(container2.getId())
            .exec();

    ContainerNetwork linkNet = inspectContainerResponse2.getNetworkSettings().getNetworks().get(networkName);
    assertNotNull(linkNet);
    assertThat(linkNet.getLinks(), equalTo(new Link[]{new Link(containerName1, containerName1 + "Link")}));
}
 
Example #12
Source File: StrimziKafkaContainer.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Override
protected void containerIsStarting(InspectContainerResponse containerInfo, boolean reused) {
    super.containerIsStarting(containerInfo, reused);

    kafkaExposedPort = getMappedPort(KAFKA_PORT);

    LOGGER.info("This is mapped port {}", kafkaExposedPort);

    advertisedListeners = new StringBuilder(getBootstrapServers());

    Collection<ContainerNetwork> cns = containerInfo.getNetworkSettings().getNetworks().values();

    for (ContainerNetwork cn : cns) {
        advertisedListeners.append("," + "BROKER://").append(cn.getIpAddress()).append(":9093");
    }

    LOGGER.info("This is all advertised listeners for Kafka {}", advertisedListeners.toString());

    startZookeeper();
    startKafka();

}
 
Example #13
Source File: ConnectToNetworkCmdIT.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Test
public void connectToNetworkWithContainerNetwork() throws InterruptedException {
    assumeNotSwarm("no network in swarm", dockerRule);

    final String subnetPrefix = getFactoryType().getSubnetPrefix() + "100";
    final String networkName = "ContainerWithNetwork" + dockerRule.getKind();
    final String containerIp = subnetPrefix + ".100";

    CreateContainerResponse container = dockerRule.getClient().createContainerCmd(DEFAULT_IMAGE)
        .withCmd("sleep", "9999")
        .exec();

    dockerRule.getClient().startContainerCmd(container.getId()).exec();

    try {
        dockerRule.getClient().removeNetworkCmd(networkName).exec();
    } catch (DockerException ignore) {
    }

    CreateNetworkResponse network = dockerRule.getClient().createNetworkCmd()
        .withName(networkName)
        .withIpam(new Network.Ipam()
            .withConfig(new Network.Ipam.Config()
                .withSubnet(subnetPrefix + ".0/24")))
        .exec();

    dockerRule.getClient().connectToNetworkCmd()
        .withNetworkId(network.getId())
        .withContainerId(container.getId())
        .withContainerNetwork(new ContainerNetwork()
            .withAliases("aliasName" + dockerRule.getKind())
            .withIpamConfig(new ContainerNetwork.Ipam()
                .withIpv4Address(containerIp)))
        .exec();

    Network updatedNetwork = dockerRule.getClient().inspectNetworkCmd().withNetworkId(network.getId()).exec();

    Network.ContainerNetworkConfig containerNetworkConfig = updatedNetwork.getContainers().get(container.getId());
    assertNotNull(containerNetworkConfig);
    assertThat(containerNetworkConfig.getIpv4Address(), is(containerIp + "/24"));

    InspectContainerResponse inspectContainerResponse = dockerRule.getClient().inspectContainerCmd(container.getId()).exec();

    ContainerNetwork testNetwork = inspectContainerResponse.getNetworkSettings().getNetworks().get(networkName);
    assertNotNull(testNetwork);
    assertThat(testNetwork.getAliases(), hasItem("aliasName" + dockerRule.getKind()));
    assertThat(testNetwork.getGateway(), is(subnetPrefix + ".1"));
    assertThat(testNetwork.getIpAddress(), is(containerIp));
}
 
Example #14
Source File: ConnectToNetworkCmd.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@CheckForNull
ContainerNetwork getContainerConfig();
 
Example #15
Source File: CreateContainerCmdImpl.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public Map<String, ContainerNetwork> getEndpointsConfig() {
    return endpointsConfig;
}
 
Example #16
Source File: CreateContainerCmdImpl.java    From docker-java with Apache License 2.0 4 votes vote down vote up
public NetworkingConfig withEndpointsConfig(Map<String, ContainerNetwork> endpointsConfig) {
    this.endpointsConfig = endpointsConfig;
    return this;
}
 
Example #17
Source File: ConnectToNetworkCmdImpl.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Override
public ContainerNetwork getContainerConfig() {
    return endpointConfig;
}
 
Example #18
Source File: ConnectToNetworkCmdImpl.java    From docker-java with Apache License 2.0 4 votes vote down vote up
@Override
public ConnectToNetworkCmd withContainerNetwork(ContainerNetwork endpointConfig) {
    this.endpointConfig = endpointConfig;
    return this;
}
 
Example #19
Source File: ConnectToNetworkCmd.java    From docker-java with Apache License 2.0 votes vote down vote up
ConnectToNetworkCmd withContainerNetwork(@Nonnull ContainerNetwork endpointConfig);