Java Code Examples for com.spotify.docker.client.DockerClient#startContainer()

The following examples show how to use com.spotify.docker.client.DockerClient#startContainer() . 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: RedisContainer.java    From pay-publicapi with MIT License 6 votes vote down vote up
RedisContainer(DockerClient docker, String host) throws DockerException, InterruptedException {

        this.docker = docker;
        this.host = host;

        failsafeDockerPull(docker);
        docker.listImages(DockerClient.ListImagesParam.create("name", REDIS_IMAGE));

        final HostConfig hostConfig = HostConfig.builder().logConfig(LogConfig.create("json-file")).publishAllPorts(true).build();
        ContainerConfig containerConfig = ContainerConfig.builder()
                .image(REDIS_IMAGE)
                .hostConfig(hostConfig)
                .build();
        containerId = docker.createContainer(containerConfig).id();
        docker.startContainer(containerId);
        port = hostPortNumber(docker.inspectContainer(containerId));
        registerShutdownHook();
        waitForRedisToStart();
    }
 
Example 2
Source File: PushPullIT.java    From docker-client with Apache License 2.0 5 votes vote down vote up
private static String startAndAwaitContainer(final DockerClient client,
                                             final ContainerConfig containerConfig,
                                             final String containerName)
    throws Exception {
  final ContainerCreation creation = client.createContainer(containerConfig, containerName);
  final String containerId = creation.id();
  client.startContainer(containerId);
  awaitRunning(client, containerId);
  return containerId;
}
 
Example 3
Source File: DockerSample.java    From just-ask with Apache License 2.0 4 votes vote down vote up
private static void foo() throws Exception {
    boolean debug = Boolean.parseBoolean(System.getProperty("debug", "false"));
    String dockerHost = String.format("http://%s:%d", CENTOS, 2375);
    DockerClient docker = null;
    try {
        docker = DefaultDockerClient.builder()
            .uri(dockerHost).build();
        Info info = docker.info();
        System.err.println("Information : " + info);
        if (debug) {
            docker.pull(SELENIUM_STANDALONE_CHROME, new LoggingBuildHandler());
        } else {
            docker.pull(SELENIUM_STANDALONE_CHROME);
        }
        final ImageInfo imageInfo = docker.inspectImage(SELENIUM_STANDALONE_CHROME);
        System.err.println("Information : " + imageInfo);
        // Bind container ports to host ports
        //            final String[] ports = {Integer.toString(PortProber.findFreePort())};
        final String[] ports = {"4444"};
        final Map<String, List<PortBinding>> portBindings = new HashMap<>();
        for (String port : ports) {
            List<PortBinding> hostPorts = new ArrayList<>();
            hostPorts.add(PortBinding.of("0.0.0.0", PortProber.findFreePort()));
            portBindings.put(port, hostPorts);
        }
        //            // Bind container port 443 to an automatically allocated available host port.
        //            List<PortBinding> randomPort = new ArrayList<>();
        //            randomPort.add(PortBinding.randomPort("0.0.0.0"));
        //            portBindings.put("443", randomPort);

        System.err.println("Printing the port mappings : " + portBindings);

        final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();

        final ContainerConfig containerConfig = ContainerConfig.builder()
            .hostConfig(hostConfig)
            .image(SELENIUM_STANDALONE_CHROME).exposedPorts(ports)
            .build();

        final ContainerCreation creation = docker.createContainer(containerConfig);
        final String id = creation.id();

        // Inspect container
        final ContainerInfo containerInfo = docker.inspectContainer(id);
        System.err.println("Container Information " + containerInfo);
        String msg = "Checking to see if the container with id [" + id + "] and name [" +
            containerInfo.name() + "]...";
        System.err.println(msg);
        if (! containerInfo.state().running()) {
            // Start container
            docker.startContainer(id);
            System.err.println(containerInfo.name() + " is now running.");
        } else {
            System.err.println(containerInfo.name() + " was already running.");
        }

        System.err.println("Lets wait here !!!");
    } finally {
        if (docker != null) {
            docker.close();
        }
    }
}
 
Example 4
Source File: DockerContainer.java    From docker-elastic-agents-plugin with Apache License 2.0 4 votes vote down vote up
public static DockerContainer create(CreateAgentRequest request, PluginSettings settings, DockerClient docker,
                                     ConsoleLogAppender consoleLogAppender) throws InterruptedException, DockerException {
    String containerName = UUID.randomUUID().toString();

    HashMap<String, String> labels = labelsFrom(request);
    String imageName = image(request.properties());
    List<String> env = environmentFrom(request, settings, containerName);

    try {
        docker.inspectImage(imageName);
        if (settings.pullOnContainerCreate()) {
            consoleLogAppender.accept("Pulling a fresh version of " + imageName + ".");
            LOG.info("Pulling a fresh version of " + imageName + ".");
            docker.pull(imageName);
        }
    } catch (ImageNotFoundException ex) {
        consoleLogAppender.accept("Image " + imageName + " not found, attempting to download.");
        LOG.info("Image " + imageName + " not found, attempting to download.");
        docker.pull(imageName);
    }

    ContainerConfig.Builder containerConfigBuilder = ContainerConfig.builder();
    if (StringUtils.isNotBlank(request.properties().get("Command"))) {
        containerConfigBuilder.cmd(splitIntoLinesAndTrimSpaces(request.properties().get("Command")).toArray(new String[]{}));
    }

    final String hostConfig = request.properties().get("Hosts");
    final String reservedMemory = request.properties().get("ReservedMemory");
    final String maxMemory = request.properties().get("MaxMemory");
    final String cpus = request.properties().get("Cpus");
    final String volumeMounts = request.properties().get("Mounts");

    HostConfig.Builder hostBuilder = HostConfig.builder()
            .privileged(privileged(request.properties()))
            .extraHosts(new Hosts(hostConfig))
            .memoryReservation(new MemorySpecification(reservedMemory).getMemory())
            .memory(new MemorySpecification(maxMemory).getMemory());

    CpusSpecification cpusValue = new CpusSpecification(cpus);
    if (cpusValue.getCpus() != null) {
        hostBuilder
                .cpuPeriod(cpusValue.getCpuPeriod())
                .cpuQuota(cpusValue.getCpuQuota());
    }
    if (volumeMounts != null) {
        hostBuilder.appendBinds(Util.splitIntoLinesAndTrimSpaces(volumeMounts));
    }

    ContainerConfig containerConfig = containerConfigBuilder
            .image(imageName)
            .labels(labels)
            .env(env)
            .hostConfig(hostBuilder.build())
            .build();

    consoleLogAppender.accept(String.format("Creating container: %s", containerName));
    ContainerCreation container = docker.createContainer(containerConfig, containerName);
    String id = container.id();

    ContainerInfo containerInfo = docker.inspectContainer(id);

    LOG.debug("Created container " + containerName);
    consoleLogAppender.accept(String.format("Starting container: %s", containerName));
    docker.startContainer(containerName);
    consoleLogAppender.accept(String.format("Started container: %s", containerName));
    LOG.debug("container " + containerName + " started");
    return new DockerContainer(id, containerName, request.jobIdentifier(), containerInfo.created(), request.properties(), request.environment());
}
 
Example 5
Source File: Deployer.java    From MineCloud with ISC License 4 votes vote down vote up
public static boolean deployServer(Server server) {
    Credentials mongoCreds = MineCloud.instance().mongo().credentials();
    Credentials redisCreds = MineCloud.instance().redis().credentials();
    String name = server.type().name() + server.number();
    World defaultWorld = server.type().defaultWorld();
    ContainerConfig config = ContainerConfig.builder()
            .hostname(name)
            .image("minecloud/server")
            .openStdin(true)
            .env(new EnvironmentBuilder()
                    .append("mongo_hosts", mongoCreds.formattedHosts())
                    .append("mongo_username", mongoCreds.username())
                    .append("mongo_password", new String(mongoCreds.password()))
                    .append("mongo_database", mongoCreds.database())

                    .append("redis_host", redisCreds.hosts()[0])
                    .append("redis_password", new String(redisCreds.password()))
                    .append("SERVER_MOD", server.type().mod())
                    .append("DEDICATED_RAM", String.valueOf(server.type().dedicatedRam()))
                    .append("MAX_PLAYERS", String.valueOf(server.type().maxPlayers()))

                    .append("server_id", server.entityId())
                    .append("DEFAULT_WORLD", defaultWorld.name())
                    .append("DEFAULT_WORLD_VERSION", defaultWorld.version())
                    .build())
            .build();

    ContainerCreation creation;

    try {
        DockerClient client = MineCloudDaemon.instance().dockerClient();

        try {
            ContainerInfo info = client.inspectContainer(name);

            if (info.state().running()) {
                client.killContainer(name);
            }

            client.removeContainer(info.id());
        } catch (ContainerNotFoundException ignored) {}

        creation = client.createContainer(config, name);

        client.startContainer(creation.id(), HostConfig.builder()
                .binds("/mnt/minecloud:/mnt/minecloud")
                .publishAllPorts(true)
                .build());
    } catch (InterruptedException | DockerException ex) {
        MineCloud.logger().log(Level.SEVERE, "Was unable to create server with type " + server.type().name(),
                ex);
        return false;
    }

    MineCloud.logger().info("Started server " + server.name()
            + " with container id " + server.containerId());
    return true;
}
 
Example 6
Source File: Deployer.java    From MineCloud with ISC License 4 votes vote down vote up
public static Bungee deployBungeeCord(Network network, BungeeType type) {
    DockerClient client = MineCloudDaemon.instance().dockerClient();
    BungeeRepository repository = MineCloud.instance().mongo().repositoryBy(Bungee.class);
    Node node = MineCloudDaemon.instance().node();
    Bungee bungee = new Bungee();

    if (repository.count("_id", node.publicIp()) > 0) {
        MineCloud.logger().log(Level.WARNING, "Did not create bungee on this node; public ip is already in use");
        return null;
    }

    bungee.setId(node.publicIp());

    Credentials mongoCreds = MineCloud.instance().mongo().credentials();
    Credentials redisCreds = MineCloud.instance().redis().credentials();
    ContainerConfig config = ContainerConfig.builder()
            .image("minecloud/bungee")
            .hostname("bungee" + bungee.publicIp())
            .exposedPorts("25565")
            .openStdin(true)
            .env(new EnvironmentBuilder()
                    .append("mongo_hosts", mongoCreds.formattedHosts())
                    .append("mongo_username", mongoCreds.username())
                    .append("mongo_password", new String(mongoCreds.password()))
                    .append("mongo_database", mongoCreds.database())

                    .append("redis_host", redisCreds.hosts()[0])
                    .append("redis_password", new String(redisCreds.password()))
                    .append("DEDICATED_RAM", String.valueOf(type.dedicatedRam()))

                    .append("bungee_id", node.publicIp())
                    .build())
            .build();
    HostConfig hostConfig = HostConfig.builder()
            .binds("/mnt/minecloud:/mnt/minecloud")
            .portBindings(new HashMap<String, List<PortBinding>>() {{
                put("25565", Arrays.asList(PortBinding.of(node.publicIp(), 25565))); // I'm sorry
            }})
            .publishAllPorts(true)
            .build();

    try {
        ContainerInfo info = client.inspectContainer("bungee");

        if (info.state().running()) {
            client.killContainer("bungee");
        }

        client.removeContainer(info.id());
    } catch (DockerException | InterruptedException ignored) {}

    ContainerCreation creation;

    try {
        creation = client.createContainer(config, type.name());

        client.startContainer(creation.id(), hostConfig);
    } catch (InterruptedException | DockerException ex) {
        MineCloud.logger().log(Level.SEVERE, "Was unable to create bungee with type " + type.name(),
                ex);
        return bungee;
    }

    bungee.setNetwork(network);
    bungee.setNode(node);
    bungee.setPublicIp(node.publicIp());
    bungee.setType(type);

    repository.save(bungee);
    MineCloud.logger().info("Started bungee " + bungee.name() + " with container id " + bungee.containerId());
    return bungee;
}