¶Ô±ÈÐÂÎļþ |
| | |
| | | package com.se.docker.utils; |
| | | |
| | | import cn.hutool.core.util.ObjectUtil; |
| | | import com.github.dockerjava.api.DockerClient; |
| | | import com.github.dockerjava.api.command.*; |
| | | import com.github.dockerjava.api.model.AuthConfig; |
| | | import com.github.dockerjava.api.model.Container; |
| | | import com.github.dockerjava.api.model.PullResponseItem; |
| | | import com.github.dockerjava.core.DefaultDockerClientConfig; |
| | | import com.github.dockerjava.core.DockerClientConfig; |
| | | import com.github.dockerjava.core.DockerClientImpl; |
| | | import com.github.dockerjava.httpclient5.ApacheDockerHttpClient; |
| | | import com.github.dockerjava.transport.DockerHttpClient; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | |
| | | import java.io.BufferedOutputStream; |
| | | import java.io.FileOutputStream; |
| | | import java.io.InputStream; |
| | | import java.io.OutputStream; |
| | | import java.time.Duration; |
| | | import java.util.List; |
| | | import java.util.Objects; |
| | | import java.util.concurrent.TimeUnit; |
| | | import java.util.stream.Collectors; |
| | | |
| | | @SuppressWarnings("ALL") |
| | | public class DockerUtils { |
| | | private static volatile DockerClient dockerClient; |
| | | |
| | | private static final Logger log = LoggerFactory.getLogger(DockerUtils.class); |
| | | |
| | | /** |
| | | * vim /lib/systemd/system/docker.service |
| | | * <p> |
| | | * # é
ç½®æ®é模å¼ï¼-Håæ°æå®dockeråºç¨ç¨åºç嬿¹å¼ï¼æè
éç¨ä¸é¢çå®å
¨è¿æ¥æ¹å¼2é1 |
| | | * ExecStart=/usr/bin/dockerd -H unix://var/run/docker.sock -H tcp://0.0.0.0:2375 |
| | | * <p> |
| | | * # é
ç½®å®å
¨è¿æ¥ï¼æ³¨æè¿éç/home/user/certs/ æ ¹æ®èªå·±æ
嵿¿æ¢ä¸ºå®é
ççå¯é¥åæ¾è·¯å¾ |
| | | * ExecStart=/usr/bin/dockerd -D --tlsverify=true --tlscert=/home/user/certs/server-cert.pem --tlskey=/home/user/certs/server-key.pem --tlscacert=/home/user/certs/ca.pem -H tcp://0.0.0.0:2375 -H unix://var/run/docker.sock |
| | | * <p> |
| | | * # éè½½é
ç½®ï¼éå¯æå¡ |
| | | * systemctl daemon-reload |
| | | * systemctl restart docker |
| | | * <p> |
| | | * # æ¥ç端å£çå¬ |
| | | * netstat -nlp |grep 2375 |
| | | * <p> |
| | | * vi /etc/docker/daemon.json |
| | | * # é
ç½®insecure-registries |
| | | * { |
| | | * "insecure-registries": ["122.12.12.12:5000"], |
| | | * "registry-mirrors": ["https://xxxxx.mirror.aliyuncs.com"] |
| | | * } |
| | | * # éè½½é
ç½®ï¼éå¯æå¡ |
| | | * systemctl daemon-reload |
| | | * systemctl restart docker |
| | | */ |
| | | private DockerUtils() { |
| | | } |
| | | |
| | | private DockerUtils(String dockerHost, String dockerApiVersion, String dockerCertPath) { |
| | | Objects.requireNonNull(dockerHost, "Docker 主æºå°åä¸è½ä¸ºç©º."); |
| | | Objects.requireNonNull(dockerApiVersion, "Docker API çæ¬ä¸è½ä¸ºç©º."); |
| | | |
| | | // 使ç¨åéæ ¡éªéå®ç° Docker 客æ·ç«¯åä¾ |
| | | if (dockerClient == null) { |
| | | synchronized (DockerUtils.class) { |
| | | if (dockerClient == null) { |
| | | dockerClient = createDockerClient(dockerHost, dockerApiVersion, dockerCertPath); |
| | | } |
| | | } |
| | | } |
| | | } |
| | | |
| | | private DockerClient createDockerClient(String dockerHost, String dockerApiVersion, String dockerCertPath) { |
| | | DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder() |
| | | .withApiVersion(dockerApiVersion) |
| | | .withDockerHost(dockerHost) |
| | | //妿å¼å¯å®å
¨è¿æ¥ï¼éè¦é
ç½®è¿è¡ |
| | | .withDockerTlsVerify(true).withDockerCertPath(dockerCertPath) |
| | | .build(); |
| | | |
| | | DockerHttpClient httpClient = new ApacheDockerHttpClient.Builder() |
| | | .dockerHost(config.getDockerHost()) |
| | | .sslConfig(config.getSSLConfig()) |
| | | .maxConnections(1000) |
| | | .connectionTimeout(Duration.ofSeconds(60)) |
| | | .responseTimeout(Duration.ofMinutes(30)) |
| | | .build(); |
| | | |
| | | return DockerClientImpl.getInstance(config, httpClient); |
| | | } |
| | | |
| | | /** |
| | | * ç»å½ Docker éåä»åº |
| | | * |
| | | * @param authConfig ç»å½æéç认è¯ä¿¡æ¯ |
| | | * @throws RuntimeException ç»å½å¤±è´¥æ¶æåºå¼å¸¸ |
| | | */ |
| | | public void login(AuthConfig authConfig) { |
| | | try { |
| | | Objects.requireNonNull(authConfig, "认è¯ä¿¡æ¯ä¸è½ä¸ºç©º."); |
| | | log.info("å¼å§ç»å½éåä»åºï¼{};username:{};password:{}", authConfig.getRegistryAddress(), authConfig.getUsername(), authConfig.getPassword()); |
| | | |
| | | dockerClient.authCmd() |
| | | .withAuthConfig(authConfig) |
| | | .exec(); |
| | | log.info("éåä»åºç»å½æåï¼{}", authConfig.getRegistryAddress()); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | throw new RuntimeException("éåä»åºç»å½å¤±è´¥ï¼" + e.getMessage()); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * ä»registryæåDockeréå |
| | | * |
| | | * @param tag éååç§° |
| | | * @return true表示æåæåï¼false表示æå失败 |
| | | */ |
| | | public void pullImage(AuthConfig authConfig, String tag) { |
| | | Objects.requireNonNull(authConfig, "认è¯ä¿¡æ¯ä¸è½ä¸ºç©º."); |
| | | if (ObjectUtil.isEmpty(tag)) { |
| | | throw new RuntimeException("éåä¿¡æ¯ä¸è½ä¸ºç©º"); |
| | | } |
| | | log.info("å¼å§æå Docker éå: {}", tag); |
| | | try { |
| | | PullImageResultCallback exec = new PullImageResultCallback() { |
| | | @Override |
| | | public void onNext(PullResponseItem item) { |
| | | System.out.println(item.getStatus()); |
| | | } |
| | | }; |
| | | PullImageCmd pullImageCmd = dockerClient.pullImageCmd(tag); |
| | | pullImageCmd.withAuthConfig(authConfig) |
| | | .exec(exec) |
| | | .awaitCompletion(30, TimeUnit.MINUTES); |
| | | exec.close(); |
| | | log.info("éåæåæåï¼{};", tag); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | throw new RuntimeException("éåæå失败ï¼{}" + e.getMessage()); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * ä¿åDockeréå |
| | | * |
| | | * @param imageId éåId |
| | | * @param filePath ä¿åæä»¶å |
| | | * @return true表示ä¿åæåï¼false表示ä¿å失败 |
| | | */ |
| | | public void saveImage(java.lang.String imageId, String filePath) { |
| | | |
| | | if (ObjectUtil.isEmpty(filePath)) { |
| | | throw new RuntimeException("åæ°é误ï¼ä¿åè·¯å¾ä¸è½ä¸ºç©º"); |
| | | } |
| | | log.info("å¼å§ä¿åéåï¼{}", imageId); |
| | | try (OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath)); |
| | | InputStream inputStream = dockerClient.saveImageCmd(imageId) |
| | | .exec()) { |
| | | if (null == inputStream) { |
| | | throw new RuntimeException("æ æ³è·åéå"); |
| | | } |
| | | byte[] bytesArray = new byte[4096]; |
| | | int bytesRead = -1; |
| | | while ((bytesRead = inputStream.read(bytesArray)) != -1) { |
| | | outputStream.write(bytesArray, 0, bytesRead); |
| | | } |
| | | log.info("éåä¿åæåï¼{}", imageId); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | throw new RuntimeException("ä¿åéåå¼å¸¸ï¼" + e.getMessage()); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * å é¤Dockeréå |
| | | * |
| | | * @param imageId éåæ ç¾ |
| | | * @return true表示å 餿åï¼false表示å é¤å¤±è´¥ |
| | | */ |
| | | public boolean removeImage(String imageId) { |
| | | Objects.requireNonNull(imageId, "éå ID ä¸è½ä¸ºç©º."); |
| | | log.info("å¼å§å é¤ Docker éå: {}", imageId); |
| | | try { |
| | | // 妿éåå½åæå®¹å¨å¨è¿è¡ï¼åä¸è¿è¡å é¤æä½ |
| | | if (isRunContainer(imageId)) { |
| | | log.warn("Docker é忣å¨ä½¿ç¨ä¸ï¼æ æ³å é¤: {}", imageId); |
| | | return false; |
| | | } |
| | | RemoveImageCmd removeImageCmd = dockerClient.removeImageCmd(imageId); |
| | | removeImageCmd.exec(); |
| | | log.info("Docker éåå 餿å: {}", imageId); |
| | | return true; |
| | | } catch (Exception e) { |
| | | log.error("Docker éåå é¤å¤±è´¥: {};{}", imageId, e.getMessage()); |
| | | return false; |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * è·åææ Docker 容å¨çä¿¡æ¯ |
| | | * |
| | | * @return ææ Docker 容å¨çä¿¡æ¯å表 |
| | | */ |
| | | public List<Container> listContainers() { |
| | | log.info("å¼å§è·åææ Docker 容å¨ä¿¡æ¯."); |
| | | try { |
| | | ListContainersCmd listContainersCmd = dockerClient.listContainersCmd(); |
| | | return listContainersCmd.exec(); |
| | | } catch (Exception e) { |
| | | log.error("è·åææ Docker 容å¨ä¿¡æ¯å¤±è´¥: {}", e.getMessage()); |
| | | throw new RuntimeException("è·åææ Docker 容å¨ä¿¡æ¯å¤±è´¥: " + e.getMessage()); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * æ¯å¦æå¨è¿è¡çå®¹å¨ |
| | | * |
| | | * @param imageId |
| | | * @return |
| | | */ |
| | | public boolean isRunContainer(String imageId) { |
| | | Objects.requireNonNull(imageId, "éå ID ä¸è½ä¸ºç©º."); |
| | | log.info("æ£æ¥ Docker é忝妿£å¨ä½¿ç¨ä¸: {}", imageId); |
| | | try { |
| | | List<Container> containers = listContainers(); |
| | | List<String> containerNames = containers.stream() |
| | | .map(Container::getImageId) |
| | | .collect(Collectors.toList()); |
| | | log.info("ååºææå®¹å¨æåï¼æ°éï¼{}", containerNames.size()); |
| | | if (ObjectUtil.isNotEmpty(containerNames) && containerNames.contains(imageId)) { |
| | | return true; |
| | | } |
| | | return false; |
| | | } catch (Exception e) { |
| | | log.error("æ£æ¥ Docker é忝妿£å¨ä½¿ç¨ä¸å¤±è´¥: {}", e.getMessage()); |
| | | throw new RuntimeException("æ£æ¥ Docker é忝妿£å¨ä½¿ç¨ä¸å¤±è´¥: " + e.getMessage()); |
| | | } |
| | | |
| | | } |
| | | |
| | | /** |
| | | * æ¨ééå |
| | | * |
| | | * @param authConfig |
| | | * @param tag |
| | | */ |
| | | public static void pushImage(AuthConfig authConfig, String tag) { |
| | | Objects.requireNonNull(authConfig, "认è¯ä¿¡æ¯ä¸è½ä¸ºç©º."); |
| | | Objects.requireNonNull(tag, "éåä¿¡æ¯ä¸è½ä¸ºç©º."); |
| | | log.info("å¼å§æ¨é Docker éå: {}", tag); |
| | | try { |
| | | PushImageCmd pushImageCmd = dockerClient.pushImageCmd(tag); |
| | | pushImageCmd.withAuthConfig(authConfig) |
| | | .start() |
| | | .awaitCompletion(30, TimeUnit.SECONDS); |
| | | log.info("éåpushæå:{}", tag); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | throw new RuntimeException("éåpush失败ï¼{}" + e.getMessage()); |
| | | } |
| | | } |
| | | |
| | | /** |
| | | * è·åéåId |
| | | * |
| | | * @param tag |
| | | * @return |
| | | */ |
| | | public String getImageId(String tag) { |
| | | try { |
| | | InspectImageCmd inspectImageCmd = dockerClient.inspectImageCmd(tag); |
| | | InspectImageResponse image = inspectImageCmd.exec(); |
| | | if (null == image) { |
| | | throw new RuntimeException("æªè·åå°éåä¿¡æ¯ï¼"); |
| | | } |
| | | return image.getId(); |
| | | } catch (Exception e) { |
| | | e.printStackTrace(); |
| | | throw new RuntimeException("æ æ³è·åéåä¿¡æ¯ï¼" + e.getMessage()); |
| | | } |
| | | |
| | | } |
| | | |
| | | // ä½¿ç¨ Builder æ¨¡å¼æå»º DockerUtil 对象 |
| | | public static class Builder { |
| | | |
| | | private String dockerHost; |
| | | private String dockerApiVersion; |
| | | private String dockerCertPath; |
| | | |
| | | public Builder withDockerHost(String dockerHost) { |
| | | this.dockerHost = dockerHost; |
| | | return this; |
| | | } |
| | | |
| | | public Builder withDockerApiVersion(String dockerApiVersion) { |
| | | this.dockerApiVersion = dockerApiVersion; |
| | | return this; |
| | | } |
| | | |
| | | public Builder withDockerCertPath(String dockerCertPath) { |
| | | this.dockerCertPath = dockerCertPath; |
| | | return this; |
| | | } |
| | | |
| | | public DockerUtils build() { |
| | | return new DockerUtils(dockerHost, dockerApiVersion, dockerCertPath); |
| | | } |
| | | } |
| | | |
| | | public static void main2(String[] args) throws InterruptedException { |
| | | String tag = "10.20.152.16:18080/test/redis:t1"; |
| | | AuthConfig authConfig = new AuthConfig() |
| | | .withRegistryAddress("10.20.152.16:18080") |
| | | .withUsername("admin") |
| | | .withPassword("admin123"); |
| | | |
| | | DockerUtils dockerUtil = new DockerUtils.Builder() |
| | | //æå¡å¨ip |
| | | .withDockerHost("tcp://10.50.80.165:2375") |
| | | //APIçæ¬ å¯éè¿å¨æå¡å¨ docker version å½ä»¤æ¥ç |
| | | .withDockerApiVersion("1.41") |
| | | //å®å
¨è¿æ¥å¯é¥æä»¶åæ¾è·¯å¾ |
| | | .withDockerCertPath("/home/user/certs/") |
| | | .build(); |
| | | //ç»å½ |
| | | dockerUtil.login(authConfig); |
| | | |
| | | /* DockerUtil.pushImage(authConfig , tag); */ |
| | | //æåéå |
| | | dockerUtil.pullImage(authConfig, tag); |
| | | String imageId1 = dockerUtil.getImageId(tag); |
| | | |
| | | //ä¿åéå |
| | | dockerUtil.saveImage(imageId1, "E:\\pdfTest\\docker\\redis.tar"); |
| | | //å é¤éå |
| | | dockerUtil.removeImage(imageId1); |
| | | } |
| | | } |