com.github.dockerjava.api.model.ExposedPort Java Examples
The following examples show how to use
com.github.dockerjava.api.model.ExposedPort.
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: DockerClientJavaApi.java From doclipser with Eclipse Public License 1.0 | 6 votes |
@Override public void defaultRunCommand(String eclipseProjectName, String dockerBuildContext) { ExposedPort tcp8080 = ExposedPort.tcp(8080); CreateContainerResponse container = dockerClient.createContainerCmd("mariolet/my-tomcat") .withCmd("true") .withExposedPorts(tcp8080) .exec(); Ports portBindings = new Ports(); portBindings.bind(tcp8080, Ports.Binding(80)); dockerClient.startContainerCmd(container.getId()) .withPortBindings(portBindings) .exec(); }
Example #2
Source File: DockerComputerSSHConnectorTest.java From docker-plugin with MIT License | 6 votes |
@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 #3
Source File: DockerComputerSSHConnector.java From docker-plugin with MIT License | 6 votes |
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 #4
Source File: DockerComputerSSHConnector.java From docker-plugin with MIT License | 6 votes |
@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 #5
Source File: ApplicationContainer.java From microshed-testing with Apache License 2.0 | 6 votes |
public DefaultServerAdapter() { if (isHollow) { defaultHttpPort = -1; } else { InspectImageResponse imageData = DockerClientFactory.instance().client().inspectImageCmd(getDockerImageName()).exec(); LOG.info("Found exposed ports: " + Arrays.toString(imageData.getContainerConfig().getExposedPorts())); int bestChoice = -1; for (ExposedPort exposedPort : imageData.getContainerConfig().getExposedPorts()) { int port = exposedPort.getPort(); // If any ports end with 80, assume they are HTTP ports if (Integer.toString(port).endsWith("80")) { bestChoice = port; break; } else if (bestChoice == -1) { // if no ports match *80, then pick the first port bestChoice = port; } } defaultHttpPort = bestChoice; LOG.info("Automatically selecting default HTTP port: " + defaultHttpPort); } }
Example #6
Source File: StartContainerCmdIT.java From docker-java with Apache License 2.0 | 6 votes |
@Test(expected = InternalServerErrorException.class) public void startContainerWithConflictingPortBindings() throws DockerException { ExposedPort tcp22 = ExposedPort.tcp(22); ExposedPort tcp23 = ExposedPort.tcp(23); Ports portBindings = new Ports(); portBindings.bind(tcp22, Binding.bindPort(11022)); portBindings.bind(tcp23, Binding.bindPort(11022)); CreateContainerResponse container = dockerRule.getClient().createContainerCmd("busybox").withCmd("true") .withExposedPorts(tcp22, tcp23).withHostConfig(newHostConfig() .withPortBindings(portBindings)) .exec(); LOG.info("Created container {}", container.toString()); assertThat(container.getId(), not(is(emptyString()))); dockerRule.getClient().startContainerCmd(container.getId()).exec(); }
Example #7
Source File: DockerBridgeTest.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
@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: ContainerState.java From testcontainers-java with MIT License | 6 votes |
/** * 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 #9
Source File: SyndesisIntegrationRuntimeContainer.java From syndesis with Apache License 2.0 | 6 votes |
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 #10
Source File: SyndesisServerContainer.java From syndesis with Apache License 2.0 | 6 votes |
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 #11
Source File: ConsulContainer.java From minimesos with Apache License 2.0 | 6 votes |
@Override protected CreateContainerCmd dockerCommand() { int port = getServicePort(); ExposedPort exposedPort = ExposedPort.tcp(port); Ports portBindings = new Ports(); if (getCluster().isMapPortsToHost()) { portBindings.bind(exposedPort, Ports.Binding.bindPort(port)); } ExposedPort consulHTTPPort = ExposedPort.tcp(ConsulConfig.CONSUL_HTTP_PORT); ExposedPort consulDNSPort = ExposedPort.udp(ConsulConfig.CONSUL_DNS_PORT); return DockerClientFactory.build().createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withName(getName()) .withCmd("agent", "-server", "-bootstrap", "-client", "0.0.0.0") .withExposedPorts(consulHTTPPort, consulDNSPort) .withPortBindings(portBindings); }
Example #12
Source File: MesosMasterContainer.java From minimesos with Apache License 2.0 | 6 votes |
@Override protected CreateContainerCmd dockerCommand() { int port = getServicePort(); ExposedPort exposedPort = ExposedPort.tcp(port); Ports portBindings = new Ports(); if (getCluster().isMapPortsToHost()) { portBindings.bind(exposedPort, Ports.Binding.bindPort(port)); } CreateContainerCmd cmd = DockerClientFactory.build().createContainerCmd(getImageName() + ":" + getImageTag()) .withName(getName()) .withExposedPorts(new ExposedPort(getServicePort())) .withEnv(newEnvironment() .withValues(getMesosMasterEnvVars()) .withValues(getSharedEnvVars()) .createEnvironment()) .withPortBindings(portBindings); MesosDns mesosDns = getCluster().getMesosDns(); if (mesosDns != null) { cmd.withDns(mesosDns.getIpAddress()); } return cmd; }
Example #13
Source File: HelloWorldContainer.java From minimesos with Apache License 2.0 | 5 votes |
@Override protected CreateContainerCmd dockerCommand() { ExposedPort exposedPort = ExposedPort.tcp(SERVICE_PORT); // port mapping is not used as port 80 is ofthen occupied on host return DockerClientFactory.build().createContainerCmd(HELLO_WORLD_IMAGE) .withEnv(String.format("SERVICE_%d_NAME=%s", SERVICE_PORT, SERVICE_NAME)) .withPrivileged(true) .withName(getName()) .withExposedPorts(exposedPort); }
Example #14
Source File: MarathonContainer.java From minimesos with Apache License 2.0 | 5 votes |
@Override protected CreateContainerCmd dockerCommand() { ExposedPort exposedPort = ExposedPort.tcp(MARATHON_PORT); Ports portBindings = new Ports(); if (getCluster().isMapPortsToHost()) { portBindings.bind(exposedPort, Ports.Binding.bindPort(MARATHON_PORT)); } return DockerClientFactory.build().createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withName(getName()) .withExtraHosts("minimesos-zookeeper:" + this.zooKeeper.getIpAddress()) .withCmd(CollectionsUtils.splitCmd(config.getCmd())) .withExposedPorts(exposedPort) .withPortBindings(portBindings); }
Example #15
Source File: MesosAgentContainer.java From minimesos with Apache License 2.0 | 5 votes |
@Override protected CreateContainerCmd dockerCommand() { ArrayList<ExposedPort> exposedPorts = new ArrayList<>(); exposedPorts.add(new ExposedPort(getServicePort())); ArrayList<Integer> resourcePorts = ResourceUtil.parsePorts(getResources()); for (Integer port : resourcePorts) { exposedPorts.add(new ExposedPort(port)); } return getBaseCommand() .withExposedPorts(exposedPorts.toArray(new ExposedPort[exposedPorts.size()])); }
Example #16
Source File: ZooKeeperContainer.java From minimesos with Apache License 2.0 | 5 votes |
@Override protected CreateContainerCmd dockerCommand() { int port = getServicePort(); ExposedPort exposedPort = ExposedPort.tcp(port); Ports portBindings = new Ports(); if (getCluster().isMapPortsToHost()) { portBindings.bind(exposedPort, Ports.Binding.bindPort(port)); } return DockerClientFactory.build().createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withName(getName()) .withExposedPorts(new ExposedPort(ZooKeeperConfig.DEFAULT_ZOOKEEPER_PORT), new ExposedPort(2888), new ExposedPort(3888)) .withPortBindings(portBindings); }
Example #17
Source File: MesosClusterTest.java From minimesos with Apache License 2.0 | 5 votes |
@Test public void dockerExposeResourcesPorts() throws Exception { List<MesosAgent> containers = CLUSTER.getAgents(); for (MesosAgent container : containers) { ArrayList<Integer> ports = ResourceUtil.parsePorts(container.getResources()); InspectContainerResponse response = DockerClientFactory.build().inspectContainerCmd(container.getContainerId()).exec(); Map bindings = response.getNetworkSettings().getPorts().getBindings(); for (Integer port : ports) { Assert.assertTrue(bindings.containsKey(new ExposedPort(port))); } } }
Example #18
Source File: MesosDnsContainer.java From minimesos with Apache License 2.0 | 5 votes |
@Override protected CreateContainerCmd dockerCommand() { return DockerClientFactory.build() .createContainerCmd(config.getImageName() + ":" + config.getImageTag()) .withEnv(newEnvironment() .withValues(getMesosDNSEnvVars()) .createEnvironment()) .withCmd("-v=2", "-config=/etc/mesos-dns/config.json") .withExposedPorts(new ExposedPort(Integer.valueOf(DNS_PORT), InternetProtocol.UDP), new ExposedPort(Integer.valueOf(DNS_PORT), InternetProtocol.TCP)) .withName(getName()); }
Example #19
Source File: ContainerState.java From testcontainers-java with MIT License | 5 votes |
/** * @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 #20
Source File: LogstashSchedulerContainer.java From logstash with Apache License 2.0 | 5 votes |
@Override protected CreateContainerCmd dockerCommand() { final String[] cmd = asList( "--mesos.master=" + mesosMasterIpAddress + ":5050", "--mesos.zookeeper.server=" + zookeeperIpAddress + ":2181", mesosRole.map(role -> "--mesos-role=" + role).orElse(null), "--enable.failover=false", elasticsearchHost.map(host -> "--logstash.elasticsearch-host=" + host).orElse(null), "--executor.heap-size=64", "--logstash.heap-size=256", "--enable.docker=" + useDocker, logstashConfig.map(file -> "--logstash.config-file=/config/" + file.getName()).orElse(null), withSyslog ? "--enable.syslog=true" : null ).stream().filter(StringUtils::isNotEmpty).toArray(String[]::new); final CreateContainerCmd containerCmd = dockerClient.createContainerCmd(SCHEDULER_IMAGE); logstashConfig.ifPresent(file -> { try { containerCmd.withBinds(new Bind(file.getParentFile().getCanonicalPath(), new Volume("/config"), AccessMode.ro)); } catch (IOException e) { throw new IllegalStateException("Path error", e); } }); return containerCmd .withName(SCHEDULER_NAME + "_" + new SecureRandom().nextInt()) .withExposedPorts(ExposedPort.tcp(9092)) .withCmd(cmd); }
Example #21
Source File: DockerConnector.java From cloudml with GNU Lesser General Public License v3.0 | 5 votes |
public String createContainerWithPorts(String image, int[] ports, String... command){ ExposedPort[] exposedPorts=new ExposedPort[ports.length]; for(int i=0;i < ports.length;i++){ exposedPorts[i]=ExposedPort.tcp(ports[i]); } CreateContainerResponse container = dockerClient.createContainerCmd(image) .withCmd(command) .withExposedPorts(exposedPorts) .exec(); return container.getId(); }
Example #22
Source File: DockerBridgeTest.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
@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 #23
Source File: BesuNode.java From ethsigner with Apache License 2.0 | 5 votes |
private int portSpec(final Ports ports, final int exposedPort) { final Binding[] tcpPorts = ports.getBindings().get(ExposedPort.tcp(exposedPort)); assertThat(tcpPorts).isNotEmpty(); assertThat(tcpPorts.length).isEqualTo(1); return Integer.parseInt(tcpPorts[0].getHostPortSpec()); }
Example #24
Source File: ResultCallback.java From Core with MIT License | 5 votes |
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 #25
Source File: KubernetesTestUtils.java From module-ballerina-kubernetes with Apache License 2.0 | 5 votes |
/** * Get the list of exposed ports of the docker image. * * @param imageName The docker image name. * @return Exposed ports. */ public static List<String> getExposedPorts(String imageName) { InspectImageResponse dockerImage = getDockerImage(imageName); if (null == dockerImage.getConfig()) { return new ArrayList<>(); } ExposedPort[] exposedPorts = dockerImage.getConfig().getExposedPorts(); return Arrays.stream(exposedPorts).map(ExposedPort::toString).collect(Collectors.toList()); }
Example #26
Source File: KnativeTestUtils.java From module-ballerina-kubernetes with Apache License 2.0 | 5 votes |
/** * Get the list of exposed ports of the docker image. * * @param imageName The docker image name. * @return Exposed ports. */ public static List<String> getExposedPorts(String imageName) { InspectImageResponse dockerImage = getDockerImage(imageName); if (null == dockerImage.getConfig()) { return new ArrayList<>(); } ExposedPort[] exposedPorts = dockerImage.getConfig().getExposedPorts(); return Arrays.stream(exposedPorts).map(ExposedPort::toString).collect(Collectors.toList()); }
Example #27
Source File: DockerTestUtils.java From module-ballerina-docker with Apache License 2.0 | 5 votes |
/** * Get the list of exposed ports of the docker image. * * @param imageName The docker image name. * @return Exposed ports. */ public static List<String> getExposedPorts(String imageName) { InspectImageResponse dockerImage = getDockerImage(imageName); if (null == dockerImage.getConfig() || null == dockerImage.getConfig().getExposedPorts()) { return new ArrayList<>(); } ExposedPort[] exposedPorts = dockerImage.getConfig().getExposedPorts(); return Arrays.stream(exposedPorts).map(ExposedPort::toString).collect(Collectors.toList()); }
Example #28
Source File: DockerTestUtils.java From module-ballerina-docker with Apache License 2.0 | 5 votes |
/** * 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 #29
Source File: SyndesisDbContainer.java From syndesis with Apache License 2.0 | 5 votes |
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 #30
Source File: DefaultDockerClient.java From junit5-docker with Apache License 2.0 | 5 votes |
private Ports createPortBindings(PortBinding... portBinding) { Ports bindings = new Ports(); for (PortBinding binding : portBinding) { ExposedPort inner = tcp(binding.inner); bindings.bind(inner, bindPort(binding.exposed)); } return bindings; }