public class DockerClientService {

    1. private static final Logger LOGGER = LoggerFactory.getLogger(DockerClientService.class);
    2. /**
    3. * 连接docker服务器
    4. *
    5. * @return
    6. */
    7. public DockerClient connectDocker(String serverUrl) {
    8. DockerClient dockerClient = DockerClientBuilder.getInstance(serverUrl).build();
    9. Info info = dockerClient.infoCmd().exec();
    10. LOGGER.debug("================= Docker环境信息:================= \n{}", info);
    11. return dockerClient;
    12. }
    13. /**
    14. * 创建容器
    15. *
    16. * @param client
    17. * @param containerName
    18. * @param imageName
    19. * @param exposedTcpPort
    20. * @param bindTcpPort
    21. * @return
    22. */
    23. public CreateContainerResponse createContainer(DockerClient client, String containerName, String imageName,
    24. int exposedTcpPort, int bindTcpPort) {
    25. ExposedPort exposedPort = ExposedPort.tcp(exposedTcpPort);
    26. Ports portBindings = new Ports();
    27. portBindings.bind(exposedPort, Ports.Binding.bindPort(bindTcpPort));
    28. CreateContainerResponse container = client.createContainerCmd(imageName)
    29. .withName(containerName)
    30. .withHostConfig(HostConfig.newHostConfig().withPortBindings(portBindings))
    31. .withExposedPorts(exposedPort).exec();
    32. return container;
    33. }
    34. /**
    35. * 创建容器
    36. *
    37. * @param client
    38. * @param containerName
    39. * @param imageName
    40. * @return
    41. */
    42. public CreateContainerResponse createContainer(DockerClient client, String containerName, String imageName) {
    43. CreateContainerResponse container = client.createContainerCmd(imageName)
    44. .withName(containerName).exec();
    45. return container;
    46. }
    47. /**
    48. * 启动容器
    49. *
    50. * @param client
    51. * @param containerId
    52. */
    53. public void startContainer(DockerClient client, String containerId) {
    54. client.startContainerCmd(containerId).exec();
    55. }
    56. /**
    57. * 停止容器
    58. *
    59. * @param client
    60. * @param containerId
    61. */
    62. public void stopContainer(DockerClient client, String containerId) {
    63. client.stopContainerCmd(containerId).exec();
    64. }
    65. /**
    66. * 重启容器
    67. *
    68. * @param client
    69. * @param containerId
    70. */
    71. public void restartContainer(DockerClient client, String containerId) {
    72. client.restartContainerCmd(containerId).exec();
    73. }
    74. /**
    75. * 删除容器
    76. *
    77. * @param client
    78. * @param containerId
    79. */
    80. public void removeContainer(DockerClient client, String containerId) {
    81. client.removeContainerCmd(containerId).exec();
    82. }

    }