java使用docker操作镜像的简单示例

 

首先需要将放开docke的2375端口,提供docker外部访问

1、编辑docker文件:/usr/lib/systemd/system/docker.service

     在ExecStart中增加 -H tcp://0.0.0.0:2375

ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock -H fd:// --containerd=/run/containerd/containerd.sock

2、刷新配置文件,重启docker

systemctl daemon-reload
systemctl restart docker

3、在浏览器中输入http://ip:2375/info,返回docker信息,即端口已经开放

 

4、接下来在java项目的pom文件中引用Docker-java包:

<dependency>
   <groupId>com.github.docker-java</groupId>
   <artifactId>docker-java</artifactId>
   <version>3.1.5</version>
</dependency>

操作镜像的代码示例:

public class DockerClientService {

    public static DockerClient connectDocker(){
        DockerClient dockerClient = DockerClientBuilder.getInstance("tcp://127.0.0.1:2375/").build();
        Info info = dockerClient.infoCmd().exec();
        System.out.println("docker的环境信息如下:=================");
        System.out.println(info);
        return dockerClient;
    }
    public static BuildImageResultCallback callback = new BuildImageResultCallback() {
        @Override
        public void onNext(BuildResponseItem item) {
            System.out.println("" + item);
            super.onNext(item);
        }
    };

    public static PushImageResultCallback push = new PushImageResultCallback() {
        @Override
        public void onNext(PushResponseItem item) {
            System.out.println("id:" + item.getId()  +" status: "+item.getStatus());
            super.onNext(item);
        }
        @Override
        public void onComplete() {
            System.out.println("Image pushed completed!");
            super.onComplete();
        }
    };

    //镜像仓库配置
    public static AuthConfig authConfig = new AuthConfig()
            .withUsername("registryUserName")
            .withPassword("registryPassword")
            .withRegistryAddress("registry.local");

    public static void main(String[] args) throws IOException {
        DockerClient dockerClient = connectDocker();
        //docker build
        File file = new File("C:/Users/Administrator/Desktop/postgresDockerFile");
        dockerClient.buildImageCmd(file).withTag("registry.local/pgsql:0.0.1").exec(callback).awaitImageId();

        //docker save
        SaveImageCmd saveImage = dockerClient.saveImageCmd("data-front").withTag("v11");
        InputStream input = saveImage.exec();
        writeToLocal("C:/Users/Administrator/Desktop/data-front",input);

        //docker tag
        dockerClient.tagImageCmd("postgres:9.6","registry.local/postgres","9.6").exec();

        //docker push
        dockerClient.pushImageCmd("registry.local/postgres:9.6").withAuthConfig(authConfig).exec(push).awaitSuccess();

        //docker load
        File dockerImageFile = new File("C:/Users/Administrator/Desktop/data-front");
        InputStream in = new FileInputStream(dockerImageFile);
        dockerClient.loadImageCmd(in).exec();

        //docker rmi
        dockerClient.removeImageCmd("registry.local/data-front:0.0.1").exec();

        //image list
        List<Image> exec = dockerClient.listImagesCmd().exec();

    }

    /**
     * 将InputStream写入本地文件
     * @param destination 写入本地目录
     * @param input 输入流
     * @throws IOException IOException
     */
    public static void writeToLocal(String destination, InputStream input)
            throws IOException {
        int index;
        byte[] bytes = new byte[1024];
        FileOutputStream downloadFile = new FileOutputStream(destination);
        while ((index = input.read(bytes)) != -1) {
            downloadFile.write(bytes, 0, index);
            downloadFile.flush();
        }
        input.close();
        downloadFile.close();

    }
}

 

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用 Java 代码来获取 Docker 镜像的 manifest。以下是一个示例代码: ```java import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.IOUtils; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class DockerManifest { public static void main(String[] args) throws NoSuchAlgorithmException, IOException { String imageName = "nginx"; // 镜像名称 String imageTag = "latest"; // 镜像标签 String manifest = getManifest(imageName, imageTag); System.out.println("Manifest: " + manifest); } public static String getManifest(String imageName, String imageTag) throws NoSuchAlgorithmException, IOException { String imageReference = imageName + ":" + imageTag; String encodedReference = Base64.getUrlEncoder().encodeToString(imageReference.getBytes()); String endpoint = "https://registry-1.docker.io/v2"; String path = "/" + imageName + "/manifests/" + imageTag; String url = endpoint + path; MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(("GET\n\n\napplication/vnd.docker.distribution.manifest.v2+json\n" + "Accept: application/vnd.docker.distribution.manifest.v2+json\n" + "Docker-Content-Digest:" + encodedReference + "\n" + path).getBytes(StandardCharsets.UTF_8)); String digest = Hex.encodeHexString(md.digest()); // 发送请求 OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .header("Accept", "application/vnd.docker.distribution.manifest.v2+json") .header("Authorization", "Bearer " + getAuthToken()) .header("Docker-Content-Digest", encodedReference) .header("Content-Type", "application/vnd.docker.distribution.manifest.v2+json") .header("Digest", "sha256:" + digest) .build(); Response response = client.newCall(request).execute(); String responseBody = response.body().string(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); Object json = gson.fromJson(responseBody, Object.class); return gson.toJson(json); } private static String getAuthToken() throws IOException { String endpoint = "https://auth.docker.io/token"; String scope = "repository:library/*:pull"; String service = "registry.docker.io"; String url = endpoint + "?scope=" + scope + "&service=" + service; OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); String responseBody = response.body().string(); Gson gson = new Gson(); AuthTokenResponse authTokenResponse = gson.fromJson(responseBody, AuthTokenResponse.class); return authTokenResponse.getToken(); } static class AuthTokenResponse { private String token; public String getToken() { return token; } public void setToken(String token) { this.token = token; } } } ``` 该代码使用了 okhttp 和 Gson 库来发送 HTTP 请求并解析 JSON 响应。您需要将 `imageName` 和 `imageTag` 替换为您自己的值。执行该代码后,将输出 Docker 镜像的 manifest。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值