com.github.dockerjava.core.DockerClientBuilder Java Examples

The following examples show how to use com.github.dockerjava.core.DockerClientBuilder. 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: docker.java    From jbang with MIT License 6 votes vote down vote up
public static void main(String[] args)
{
    final var dockerClient = DockerClientBuilder.getInstance().build();

    BuildImageResultCallback callback = new BuildImageResultCallback()
    {
        @Override
        public void onNext(BuildResponseItem item)
        {
            System.out.print(item.getStream());
            super.onNext(item);
        }
    };

    dockerClient
            .listImagesCmd()
            .exec().stream()
                .filter(s->s!=null)
                .forEach(it -> System.out.println(it.getId() + " " +
                               String.join(",", Objects.requireNonNullElse(it.getRepoTags(), new String[0]))));
}
 
Example #2
Source File: DockerOpt.java    From dew with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiates a new Docker opt.
 *
 * @param log              日志对象
 * @param host             DOCKER_HOST, e.g. tcp://10.200.131.182:2375
 * @param registryUrl      registry地址, e.g. https://harbor.dew.env/v2
 * @param registryUsername registry用户名
 * @param registryPassword registry密码
 * @see <a href="https://docs.docker.com/install/linux/linux-postinstall/#configure-where-the-docker-daemon-listens-for-connections">The Docker Daemon Listens For Connections</a>
 */
protected DockerOpt(Logger log, String host, String registryUrl, String registryUsername, String registryPassword) {
    this.log = log;
    this.registryUsername = registryUsername;
    this.registryPassword = registryPassword;
    DefaultDockerClientConfig.Builder builder = DefaultDockerClientConfig.createDefaultConfigBuilder();
    if (host != null && !host.isEmpty()) {
        builder.withDockerHost(host);
    }
    if (registryUrl != null) {
        registryUrl = registryUrl.endsWith("/") ? registryUrl.substring(0, registryUrl.length() - 1) : registryUrl;
        registryApiUrl = registryUrl.substring(0, registryUrl.lastIndexOf("/") + 1) + "api/v2.0";
        defaultAuthConfig = new AuthConfig()
                .withRegistryAddress(registryUrl)
                .withUsername(registryUsername)
                .withPassword(registryPassword);
    }
    docker = DockerClientBuilder.getInstance(builder.build()).build();
}
 
Example #3
Source File: FlinkIT.java    From flink-prometheus-example with Apache License 2.0 6 votes vote down vote up
@Test
void jobCanBeRestartedFromCheckpoint() throws UnirestException {
  await()
      .atMost(1, TimeUnit.MINUTES)
      .ignoreException(JSONException.class)
      .untilAsserted(() -> assertThat(getActiveTaskManager()).doesNotContain("unassigned"));

  final String firstActiveTaskManager = getActiveTaskManager();

  DockerClientBuilder.getInstance().build().killContainerCmd(firstActiveTaskManager).exec();

  await()
      .atMost(1, TimeUnit.MINUTES)
      .untilAsserted(
          () -> assertThat(getActiveTaskManager()).isNotEqualTo(firstActiveTaskManager));
}
 
Example #4
Source File: DockerClientConnector.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
public DockerClient getDockerClient(String registryUsername,
                                    String registryPassword,
                                    String registryEmail,
                                    String dockerCertPath,
                                    String dockerConfig,
                                    String dockerTlsVerify,
                                    String dockerHost) {
    DefaultDockerClientConfig config
            = DefaultDockerClientConfig.createDefaultConfigBuilder()
            .withRegistryEmail(registryEmail)
            .withRegistryPassword(registryPassword)
            .withRegistryUsername(registryUsername)
            .withDockerCertPath(dockerCertPath)
            .withDockerConfig(dockerConfig)
            .withDockerTlsVerify(dockerTlsVerify)
            .withDockerHost(dockerHost).build();

    return DockerClientBuilder.getInstance(config).build();
}
 
Example #5
Source File: DockerBridgeTest.java    From vertx-service-discovery with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  init();

  client = DockerClientBuilder.getInstance().build();
  List<Container> running = client.listContainersCmd().withStatusFilter(Collections.singletonList("running")).exec();
  if (running != null) {
    running.forEach(container -> client.stopContainerCmd(container.getId()).exec());
  }

  vertx = Vertx.vertx();
  discovery = ServiceDiscovery.create(vertx);
  bridge = new DockerServiceImporter();
  discovery.registerServiceImporter(bridge,
      new JsonObject().put("scan-period", -1));

  await().until(() -> bridge.started);
}
 
Example #6
Source File: DockerJavaUtil.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * 更高级的连接方式,后续使用证书需要用到
 *
 * @return
 */
public static DockerClient advanceConnect() {
    DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
            .withDockerHost("tcp://localhost:2376")
            //TODO 后续支持证书
            .withDockerTlsVerify(true)
            .withDockerCertPath("/home/user/.docker/certs")//证书?
            .withDockerConfig("/Users/vjay/.docker")
            .withApiVersion("1.30") // optional
            .withRegistryUrl("https://index.docker.io/v1/")//填私库地址
            .withRegistryUsername("username")//填私库用户名
            .withRegistryPassword("123456")//填私库密码
            .withRegistryEmail("[email protected]")//填私库注册邮箱
            .build();
    return DockerClientBuilder.getInstance(config).build();
}
 
Example #7
Source File: DockerHandler.java    From hortonmachine with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Initialize the docker client. 
 * 
 * @return an error message if there were issues, <code>null</code> if everyhtin gwent smooth.
 */
public String initDocker() {
    try {
        DefaultDockerClientConfig.Builder builder = DefaultDockerClientConfig.createDefaultConfigBuilder();
        if (OsCheck.getOperatingSystemType() == OSType.Windows) {
            builder.withDockerHost("tcp://localhost:2375");
        }
        dockerClient = DockerClientBuilder.getInstance(builder).build();

        dockerClient.versionCmd().exec();
    } catch (Exception e) {
        String msg = MSG_NOTRUNNING;
        if (OsCheck.getOperatingSystemType() == OSType.Windows) {
            msg += "\n" + MSG_WIN_SOCKET;
        }
        return msg;
    }

    return null;
}
 
Example #8
Source File: DockerUtils.java    From roboconf-platform with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a Docker client from target properties.
 * @param targetProperties a non-null map
 * @return a Docker client
 * @throws TargetException if something went wrong
 */
public static DockerClient createDockerClient( Map<String,String> targetProperties ) throws TargetException {

	// Validate what needs to be validated.
	Logger logger = Logger.getLogger( DockerHandler.class.getName());
	logger.fine( "Setting the target properties." );

	String edpt = targetProperties.get( DockerHandler.ENDPOINT );
	if( Utils.isEmptyOrWhitespaces( edpt ))
		edpt = DockerHandler.DEFAULT_ENDPOINT;

	// The configuration is straight-forward.
	Builder config =
			DefaultDockerClientConfig.createDefaultConfigBuilder()
			.withDockerHost( edpt )
			.withRegistryUsername( targetProperties.get( DockerHandler.USER ))
			.withRegistryPassword( targetProperties.get( DockerHandler.PASSWORD ))
			.withRegistryEmail( targetProperties.get( DockerHandler.EMAIL ))
			.withApiVersion( targetProperties.get( DockerHandler.VERSION ));

	// Build the client.
	DockerClientBuilder clientBuilder = DockerClientBuilder.getInstance( config.build());

	return clientBuilder.build();
}
 
Example #9
Source File: DockerClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenCreatingDockerClientWithProperties_thenReturnInstance() {

    // when
    Properties properties = new Properties();
    properties.setProperty("registry.email", "[email protected]");
    properties.setProperty("registry.url", "register.bealdung.io/v2/");
    properties.setProperty("registry.password", "strongpassword");
    properties.setProperty("registry.username", "bealdung");
    properties.setProperty("DOCKER_CERT_PATH", "/home/bealdung/public/.docker/certs");
    properties.setProperty("DOCKER_CONFIG", "/home/bealdung/public/.docker/");
    properties.setProperty("DOCKER_TLS_VERIFY", "1");
    properties.setProperty("DOCKER_HOST", "tcp://docker.bealdung.com:2376");

    DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withProperties(properties).build();

    DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

    // then
    assertNotNull(dockerClient);
}
 
Example #10
Source File: NettyDockerCmdExecFactoryConfigTest.java    From docker-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testNettyDockerCmdExecFactoryConfigWithoutApiVersion() throws Exception {
    int dockerPort = getFreePort();

    NettyDockerCmdExecFactory factory = new NettyDockerCmdExecFactory();
    Builder configBuilder = new DefaultDockerClientConfig.Builder()
        .withDockerTlsVerify(false)
        .withDockerHost("tcp://localhost:" + dockerPort);

    DockerClient client = DockerClientBuilder.getInstance(configBuilder)
        .withDockerCmdExecFactory(factory)
        .build();

    FakeDockerServer server = new FakeDockerServer(dockerPort);
    server.start();
    try {
        client.versionCmd().exec();

        List<HttpRequest> requests = server.getRequests();

        assertEquals(requests.size(), 1);
        assertEquals(requests.get(0).uri(), "/version");
    } finally {
        server.stop();
    }
}
 
Example #11
Source File: Docker.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
public DockerClient getClient() {
  if (client == null) {
    synchronized (this) {
      if (client == null) {
        execFactory = new JerseyDockerCmdExecFactory();
        DockerCmdExecFactory dockerCmdExecFactory = execFactory.withMaxPerRouteConnections(100);
        client = DockerClientBuilder.getInstance(dockerServerUrl).withDockerCmdExecFactory(dockerCmdExecFactory).build();
      }
    }
  }
  return client;
}
 
Example #12
Source File: CmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public DockerClientImpl createDockerClient(DockerClientConfig config) {
    return (DockerClientImpl) DockerClientBuilder.getInstance(config)
        .withDockerCmdExecFactory(
            new NettyDockerCmdExecFactory()
                .withConnectTimeout(30 * 1000)
        )
        .build();
}
 
Example #13
Source File: LocalCluster.java    From logstash with Apache License 2.0 5 votes vote down vote up
private void run() throws Exception {

        Runtime.getRuntime().addShutdownHook(new Thread(cluster::stop));
        cluster.start();

        MesosMaster master = cluster.getMasterContainer();

        DockerClientConfig.DockerClientConfigBuilder dockerConfigBuilder = DockerClientConfig
            .createDefaultConfigBuilder()
            .withUri("http://" + master.getIpAddress() + ":" + DOCKER_PORT);
        DockerClient clusterDockerClient = DockerClientBuilder
            .getInstance(dockerConfigBuilder.build()).build();

        DummyFrameworkContainer dummyFrameworkContainer = new DummyFrameworkContainer(
            clusterDockerClient, "dummy-framework");
        dummyFrameworkContainer.start(ClusterConfig.DEFAULT_TIMEOUT_SECS);

        String mesosZk = master.getFormattedZKAddress();

        System.setProperty("mesos.zk", mesosZk);
        System.setProperty("mesos.logstash.logstash.heap.size", "128");
        System.setProperty("mesos.logstash.executor.heap.size", "64");

        System.out.println("");
        System.out.println("Cluster Started.");
        System.out.println("MASTER URL: " + master.getFormattedZKAddress());
        System.out.println("");

        while (!Thread.currentThread().isInterrupted()) {
            Thread.sleep(5000);
            printRunningContainers(clusterDockerClient);
        }
    }
 
Example #14
Source File: DockerClientFactory.java    From minimesos with Apache License 2.0 5 votes vote down vote up
public static DockerClient build() {
    if (dockerClient == null) {
        DefaultDockerClientConfig.Builder builder = new DefaultDockerClientConfig.Builder();
        builder = builder.withApiVersion("1.12");

        String dockerHostEnv = System.getenv("DOCKER_HOST");
        if (StringUtils.isBlank(dockerHostEnv)) {
            builder.withDockerHost("unix:///var/run/docker.sock");
        }

        DockerClientConfig config = builder.build();
        dockerClient = DockerClientBuilder.getInstance(config).build();
    }
    return dockerClient;
}
 
Example #15
Source File: CmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public DockerClientImpl createDockerClient(DockerClientConfig config) {
    return (DockerClientImpl) DockerClientBuilder.getInstance(config)
        .withDockerHttpClient(
            new TrackingDockerHttpClient(
                new JerseyDockerHttpClient.Builder()
                    .dockerHost(config.getDockerHost())
                    .sslConfig(config.getSSLConfig())
                    .connectTimeout(30 * 1000)
                    .build()
            )
        )
        .build();
}
 
Example #16
Source File: DockerClientFactoryBean.java    From Dolphin with Apache License 2.0 5 votes vote down vote up
public DockerClient getObject() throws Exception {
    DockerClientConfig config = DockerClientConfig.createDefaultConfigBuilder()
            .withVersion(version)
            .withUri(uri)
            .withUsername(username)
            .withPassword(password)
            .withEmail(email)
            .withServerAddress(serverAddress)
            .withDockerCertPath(dockerCertPath)
            .build();
    return DockerClientBuilder.getInstance(config).build();
}
 
Example #17
Source File: CmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public DockerClientImpl createDockerClient(DockerClientConfig config) {
    return (DockerClientImpl) DockerClientBuilder.getInstance(config)
        .withDockerHttpClient(
            new TrackingDockerHttpClient(
                new OkDockerHttpClient.Builder()
                    .dockerHost(config.getDockerHost())
                    .sslConfig(config.getSSLConfig())
                    .connectTimeout(30 * 100)
                    .build()
            )
        )
        .build();
}
 
Example #18
Source File: ITTestBase.java    From hudi with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() {
  String dockerHost = (OVERRIDDEN_DOCKER_HOST != null) ? OVERRIDDEN_DOCKER_HOST : DEFAULT_DOCKER_HOST;
  // Assuming insecure docker engine
  DockerClientConfig config =
      DefaultDockerClientConfig.createDefaultConfigBuilder().withDockerHost(dockerHost).build();
  // using jaxrs/jersey implementation here (netty impl is also available)
  DockerCmdExecFactory dockerCmdExecFactory = new JerseyDockerCmdExecFactory().withConnectTimeout(1000)
      .withMaxTotalConnections(100).withMaxPerRouteConnections(10);
  dockerClient = DockerClientBuilder.getInstance(config).withDockerCmdExecFactory(dockerCmdExecFactory).build();
  await().atMost(60, SECONDS).until(this::servicesUp);
}
 
Example #19
Source File: CmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Override
public DockerClientImpl createDockerClient(DockerClientConfig config) {
    return (DockerClientImpl) DockerClientBuilder.getInstance(config)
        .withDockerHttpClient(
            new TrackingDockerHttpClient(
                new ApacheDockerHttpClient.Builder()
                    .dockerHost(config.getDockerHost())
                    .sslConfig(config.getSSLConfig())
                    .build()
            )
        )
        .build();
}
 
Example #20
Source File: AuthCmdIT.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Ignore("Disabled because of 500/InternalServerException")
@Test
public void testAuthInvalid() throws Exception {
    assertThrows("Wrong login/password, please try again", UnauthorizedException.class, () -> {
        DockerClientBuilder.getInstance(dockerRule.config("garbage"))
            .build()
            .authCmd()
            .exec();
    });
}
 
Example #21
Source File: MobycraftDockerClientImpl.java    From mobycraft with Apache License 2.0 5 votes vote down vote up
@Override
public DockerClient getDockerClient() {
    if (dockerClient == null) {
        ConfigProperties configProperties = configurationCommands.getConfigProperties();

        DockerClientConfig dockerConfig = DockerClientConfig
                .createDefaultConfigBuilder()
                .withUri(configProperties.getDockerHostProperty().getString())
                .withDockerCertPath(configProperties.getCertPathProperty().getString()).build();

        dockerClient = DockerClientBuilder.getInstance(dockerConfig).build();
    }
    return dockerClient;
}
 
Example #22
Source File: NettyDockerCmdExecFactoryConfigTest.java    From docker-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testNettyDockerCmdExecFactoryConfigWithApiVersion() throws Exception {
    int dockerPort = getFreePort();

    NettyDockerCmdExecFactory factory = new NettyDockerCmdExecFactory();
    Builder configBuilder = new DefaultDockerClientConfig.Builder()
        .withDockerTlsVerify(false)
        .withDockerHost("tcp://localhost:" + dockerPort)
        .withApiVersion("1.23");

    DockerClient client = DockerClientBuilder.getInstance(configBuilder)
            .withDockerCmdExecFactory(factory)
            .build();

    FakeDockerServer server = new FakeDockerServer(dockerPort);
    server.start();
    try {
        client.versionCmd().exec();

        List<HttpRequest> requests = server.getRequests();

        assertEquals(requests.size(), 1);
        assertEquals(requests.get(0).uri(), "/v1.23/version");
    } finally {
        server.stop();
    }
}
 
Example #23
Source File: SocketPoolManagerTest.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws Exception {
    SocketInitContext context = new SocketInitContext();

    DefaultDockerClientConfig config = DefaultDockerClientConfig
            .createDefaultConfigBuilder()
            .withDockerHost("unix:///var/run/docker.sock")
            .build();
    context.setClient(DockerClientBuilder.getInstance(config).build());
    manager.init(context);
}
 
Example #24
Source File: DockerClientFactory.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
private DockerClient createDockerClient(final DefaultDockerClientConfig config) {
  final DockerCmdExecFactory dockerCmdExecFactory =
      new JerseyDockerCmdExecFactory()
          .withMaxTotalConnections(100)
          .withMaxPerRouteConnections(10)
          .withReadTimeout(7500)
          .withConnectTimeout(7500);

  return DockerClientBuilder.getInstance(config)
      .withDockerCmdExecFactory(dockerCmdExecFactory)
      .build();
}
 
Example #25
Source File: DockerContainerManagementService.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
public DockerClient newDockerClient(String host) {
    String url = String.format("tcp://%s:%d", host,dockerRemoteProperties.getPort());
    if(dockerRemoteProperties.getEnableTls() == true){
        DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withDockerHost(url)
                .withDockerTlsVerify(true)
                .withDockerCertPath(dockerRemoteProperties.getCertPath())
                .build();
        return DockerClientBuilder.getInstance(config).build();
    }else{
        return DockerClientBuilder.getInstance(url).build();
    }
}
 
Example #26
Source File: DockerClientFactory.java    From Core with MIT License 5 votes vote down vote up
private static DockerClient get(
        String host,
        Boolean tlsVerify,
        String certPath,
        String registryUsername,
        String registryPass,
        String registryMail,
        String registryUrl
) {
    DefaultDockerClientConfig.Builder configBuilder = DefaultDockerClientConfig.createDefaultConfigBuilder()
            .withDockerHost(host);

    configBuilder.withDockerTlsVerify(tlsVerify);

    if (!certPath.equals("")) {
        configBuilder.withDockerCertPath(certPath);
    }

    if(!registryUrl.equals("")) {
        configBuilder.withRegistryUrl(registryUrl);
        if (!registryUsername.equals("")) {
            configBuilder.withRegistryUsername(registryUsername);
        }

        if (!registryMail.equals("")) {
            configBuilder.withRegistryEmail(registryMail);
        }

        if (!registryPass.equals("")) {
            configBuilder.withRegistryPassword(registryPass);
        }
    }

    DockerClientConfig config = configBuilder.build();

    return DockerClientBuilder.getInstance(config).build();
}
 
Example #27
Source File: SocketPoolManager.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
/**
 * Init local docker.sock api interface
 */
@Override
public void init(SocketInitContext context) throws Exception {
    DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
            .withDockerHost(context.getDockerHost()).build();

    client = DockerClientBuilder.getInstance(config).build();
}
 
Example #28
Source File: DockerClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCreatingAdvanceDockerClient_thenReturnInstance() {

    // when
    DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().withRegistryEmail("[email protected]").withRegistryUrl("register.bealdung.io/v2/").withRegistryPassword("strongpassword").withRegistryUsername("bealdung")
            .withDockerCertPath("/home/bealdung/public/.docker/certs").withDockerConfig("/home/bealdung/public/.docker/").withDockerTlsVerify("1").withDockerHost("tcp://docker.beauldung.com:2376").build();

    DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

    // then
    assertNotNull(dockerClient);
}
 
Example #29
Source File: DockerClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCreatingDockerClientWithDockerHost_thenReturnInstance() {
    // when
    DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://docker.bealdung.com:2375").build();

    // then
    assertNotNull(dockerClient);
}
 
Example #30
Source File: DockerClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCreatingDockerClient_thenReturnDefaultInstance() {

    // when
    DefaultDockerClientConfig.Builder config = DefaultDockerClientConfig.createDefaultConfigBuilder();
    DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();

    // then
    assertNotNull(dockerClient);
}