| | |
| | | package com.se.docker.service; |
| | | |
| | | import com.github.dockerjava.api.DockerClient; |
| | | import com.github.dockerjava.api.command.CreateContainerResponse; |
| | | import com.github.dockerjava.api.command.InspectContainerResponse; |
| | | import com.github.dockerjava.core.DockerClientBuilder; |
| | | import org.slf4j.Logger; |
| | | import org.slf4j.LoggerFactory; |
| | | import org.springframework.beans.factory.annotation.Value; |
| | | import org.springframework.stereotype.Service; |
| | | |
| | |
| | | //@Value("${docker.prefix}") |
| | | public String localFilePrefix; |
| | | |
| | | private static final Logger log = LoggerFactory.getLogger(SysDockerService.class); |
| | | |
| | | public String test() throws Exception { |
| | | return "docker: " + System.currentTimeMillis(); |
| | | } |
| | | |
| | | /** |
| | | * java DockerClient操作 |
| | | * https://blog.csdn.net/weixin_45198228/article/details/130060333 |
| | | */ |
| | | public void t() { |
| | | try { |
| | | // 创建Docker客户端实例 |
| | | DockerClient dockerClient = DockerClientBuilder.getInstance("unix:///var/run/docker.sock").build(); |
| | | |
| | | // 创建并启动一个新的容器 |
| | | CreateContainerResponse container = dockerClient.createContainerCmd("busybox") |
| | | .withCmd("echo", "Hello Docker!") |
| | | .exec(); |
| | | |
| | | // 启动容器 |
| | | dockerClient.startContainerCmd(container.getId()).exec(); |
| | | |
| | | // 检查容器状态 |
| | | InspectContainerResponse inspectContainerResponse = dockerClient.inspectContainerCmd(container.getId()).exec(); |
| | | System.out.println(inspectContainerResponse.toString()); |
| | | |
| | | // 停止并移除容器 |
| | | dockerClient.removeContainerCmd(container.getId()).withRemoveVolumes(true).exec(); |
| | | |
| | | // 关闭Docker客户端 |
| | | dockerClient.close(); |
| | | } catch (Exception ex) { |
| | | log.error(ex.getMessage(), ex); |
| | | } |
| | | } |
| | | } |