13693261870
2024-12-24 d877ac3faecbee5ed64bc23665347d14706663c9
操作docker容器
已添加1个文件
已修改4个文件
328 ■■■■ 文件已修改
se-common/se-common-core/src/main/java/com/se/common/core/domain/DockerContainer.java 60 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-modules/se-docker/src/main/java/com/se/docker/controller/SysDockerController.java 2 ●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-modules/se-docker/src/main/java/com/se/docker/service/SysDockerService.java 73 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-modules/se-docker/src/main/java/com/se/docker/utils/DockerUtils.java 162 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
说明.txt 31 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
se-common/se-common-core/src/main/java/com/se/common/core/domain/DockerContainer.java
¶Ô±ÈÐÂÎļþ
@@ -0,0 +1,60 @@
package com.se.common.core.domain;
@SuppressWarnings("ALL")
public class DockerContainer {
    private String id;
    private String name;
    /**
     * running,created,exited,paused,restarting,dead,error
     */
    private String state;
    /**
     * redis:latest
     */
    private String image;
    public DockerContainer() {
    }
    public DockerContainer(String id, String name, String state, String image) {
        this.id = id;
        this.name = name;
        this.state = state;
        this.image = image;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
        this.state = state;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
}
se-modules/se-docker/src/main/java/com/se/docker/controller/SysDockerController.java
@@ -29,7 +29,7 @@
            return R.ok(str);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return R.fail();
            return R.fail(e.getMessage());
        }
    }
}
se-modules/se-docker/src/main/java/com/se/docker/service/SysDockerService.java
@@ -2,25 +2,94 @@
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.PullResponseItem;
import com.github.dockerjava.core.DockerClientBuilder;
import com.se.common.core.domain.DockerContainer;
import com.se.docker.utils.DockerUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@Service
@SuppressWarnings("ALL")
public class SysDockerService {
    //@Value("${docker.prefix}")
    public String localFilePrefix;
    @Value("${docker.host}")
    private String host;
    @Value("${docker.apiVersion}")
    private String apiVersion;
    private static DockerUtils dockerUtils;
    private static final Logger log = LoggerFactory.getLogger(SysDockerService.class);
    public DockerUtils getDockerUtils() {
        if (null == dockerUtils) {
            dockerUtils = new DockerUtils(host, apiVersion);
        }
        return dockerUtils;
    }
    public String test() throws Exception {
        List<String> names = new ArrayList<>(Arrays.asList("se-redis", "se-mysql", "se-system", "se-wgcloud"));
        List<DockerContainer> list = getContainers(names);
        String id = list.get(0).getId();
        start(id);
        pause(id);
        unpause(id);
        stop(id);
        restart(id);
        return "docker: " + System.currentTimeMillis();
    }
    public List<DockerContainer> getContainers(List<String> names) {
        DockerUtils util = getDockerUtils();
        List<Container> containers = util.listContainers();
        List<DockerContainer> list = new ArrayList<>();
        for (Container container : containers) {
            if (null == container.getNames() || 0 == container.getNames().length) continue;
            String containerName = container.getNames()[0];
            for (String name : names) {
                if (containerName.contains(name)) {
                    list.add(new DockerContainer(container.getId(), containerName, container.getState(), container.getImage()));
                    break;
                }
            }
        }
        return list;
    }
    public void start(String id) {
        getDockerUtils().start(id);
    }
    public void restart(String id) {
        getDockerUtils().restart(id);
    }
    public void stop(String id) {
        getDockerUtils().stop(id);
    }
    public void pause(String id) {
        getDockerUtils().pause(id);
    }
    public void unpause(String id) {
        getDockerUtils().unpause(id);
    }
    /**
     * java DockerClient操作
     * https://blog.csdn.net/weixin_45198228/article/details/130060333
se-modules/se-docker/src/main/java/com/se/docker/utils/DockerUtils.java
@@ -59,14 +59,45 @@
    private DockerUtils() {
    }
    private DockerUtils(String dockerHost, String dockerApiVersion, String dockerCertPath) {
    public DockerUtils(String dockerHost, String dockerApiVersion) {
        Objects.requireNonNull(dockerHost, "Docker ä¸»æœºåœ°å€ä¸èƒ½ä¸ºç©º.");
        Objects.requireNonNull(dockerApiVersion, "Docker API ç‰ˆæœ¬ä¸èƒ½ä¸ºç©º.");
        // ä½¿ç”¨åŒé‡æ ¡éªŒé”å®žçް Docker å®¢æˆ·ç«¯å•例
        if (dockerClient == null) {
        if (null == dockerClient) {
            synchronized (DockerUtils.class) {
                if (dockerClient == null) {
                if (null == dockerClient) {
                    dockerClient = createDockerClient(dockerHost, dockerApiVersion);
                }
            }
        }
    }
    private DockerClient createDockerClient(String dockerHost, String dockerApiVersion) {
        DockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder()
                .withApiVersion(dockerApiVersion)
                .withDockerHost(dockerHost)
                .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);
    }
    public DockerUtils(String dockerHost, String dockerApiVersion, String dockerCertPath) {
        Objects.requireNonNull(dockerHost, "Docker ä¸»æœºåœ°å€ä¸èƒ½ä¸ºç©º.");
        Objects.requireNonNull(dockerApiVersion, "Docker API ç‰ˆæœ¬ä¸èƒ½ä¸ºç©º.");
        // ä½¿ç”¨åŒé‡æ ¡éªŒé”å®žçް Docker å®¢æˆ·ç«¯å•例
        if (null == dockerClient) {
            synchronized (DockerUtils.class) {
                if (null == dockerClient) {
                    dockerClient = createDockerClient(dockerHost, dockerApiVersion, dockerCertPath);
                }
            }
@@ -201,6 +232,28 @@
    }
    /**
     * æŽ¨é€é•œåƒ
     *
     * @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());
        }
    }
    /**
     * èŽ·å–æ‰€æœ‰ Docker å®¹å™¨çš„信息
     *
     * @return æ‰€æœ‰ Docker å®¹å™¨çš„信息列表
@@ -209,6 +262,7 @@
        log.info("开始获取所有 Docker å®¹å™¨ä¿¡æ¯.");
        try {
            ListContainersCmd listContainersCmd = dockerClient.listContainersCmd();
            listContainersCmd.withShowAll(true);
            return listContainersCmd.exec();
        } catch (Exception e) {
            log.error("获取所有 Docker å®¹å™¨ä¿¡æ¯å¤±è´¥: {}", e.getMessage());
@@ -243,28 +297,6 @@
    }
    /**
     * æŽ¨é€é•œåƒ
     *
     * @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
@@ -282,33 +314,64 @@
            e.printStackTrace();
            throw new RuntimeException("无法获取镜像信息:" + e.getMessage());
        }
    }
    // ä½¿ç”¨ Builder æ¨¡å¼æž„建 DockerUtil å¯¹è±¡
    public static class Builder {
    public void start(String id) {
        try {
            InspectContainerResponse resp = dockerClient.inspectContainerCmd(id).exec();
            if (null == resp) return;
        private String dockerHost;
        private String dockerApiVersion;
        private String dockerCertPath;
        public Builder withDockerHost(String dockerHost) {
            this.dockerHost = dockerHost;
            return this;
            dockerClient.startContainerCmd(id).exec();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        }
        public Builder withDockerApiVersion(String dockerApiVersion) {
            this.dockerApiVersion = dockerApiVersion;
            return this;
    public void restart(String id) {
        try {
            InspectContainerResponse resp = dockerClient.inspectContainerCmd(id).exec();
            if (null == resp) return;
            dockerClient.restartContainerCmd(id).exec();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        }
        public Builder withDockerCertPath(String dockerCertPath) {
            this.dockerCertPath = dockerCertPath;
            return this;
    public void stop(String id) {
        try {
            InspectContainerResponse resp = dockerClient.inspectContainerCmd(id).exec();
            if (null == resp) return;
            dockerClient.stopContainerCmd(id).exec();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
        }
        public DockerUtils build() {
            return new DockerUtils(dockerHost, dockerApiVersion, dockerCertPath);
    public void pause(String id) {
        try {
            InspectContainerResponse resp = dockerClient.inspectContainerCmd(id).exec();
            if (null == resp) return;
            if (null != resp.getState().getRunning() && resp.getState().getRunning()) {
                dockerClient.pauseContainerCmd(id).exec();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
    public void unpause(String id) {
        try {
            InspectContainerResponse resp = dockerClient.inspectContainerCmd(id).exec();
            if (null == resp) return;
            if (null != resp.getState().getPaused() && resp.getState().getPaused()) {
                dockerClient.unpauseContainerCmd(id).exec();
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }
@@ -319,14 +382,11 @@
                .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();
        DockerUtils dockerUtil = new DockerUtils(
                "tcp://192.168.11.203:2375",
                "1.45",
                "/home/user/certs/");
        //登录
        dockerUtil.login(authConfig);
˵Ã÷.txt
@@ -111,3 +111,34 @@
kill -9 10086
url: jdbc:mysql://localhost:3306/se-cloud?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
--------------------------------------------------------
vi /etc/docker/daemon.json
vim /lib/systemd/system/docker.service
# é…ç½®æ™®é€šæ¨¡å¼ï¼Œ-H参数指定docker应用程序监听方式,或者采用下面的安全连接方式2选1
ExecStart=/usr/bin/dockerd -H unix://var/run/docker.sock -H tcp://0.0.0.0:2375
#配置安全连接,注意这里的/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
#重载配置,重启服务
systemctl daemon-reload
systemctl restart docker
#查看端口监听
netstat -nlp |grep 2375
firewall-cmd --permanent --zone=public --add-port=2375/tcp
firewall-cmd --reload
firewall-cmd --list-ports
/se-cloud-se-redis-1
# se-docker-dev.yml
docker:
  host: tcp://192.168.11.203:2375
  apiVersion: 1.45
docker pause 7c5b33491640
docker unpause 7c5b33491640
--------------------------------------------------------