docker-client 应用实例

// Create a client based on DOCKER_HOST and DOCKER_CERT_PATH env vars
final DockerClient docker = DefaultDockerClient.fromEnv().build();


/**
*拉取镜像
*
/
// 1、直接拉取镜像,从dockerhub中拉取
docker.pull("busybox");


///2、私有仓库拉取镜像
// 服务器地址默认为 to "https://index.docker.io/v1/",这里可以改为自己的私有镜像仓库
RegistryAuth registryAuth = RegistryAuth.builder().email("foo@bar.com").username("foobar")
  .password("secret-password").serverAddress("https://myprivateregistry.com/v1/").build();
docker.pull("foobar/busybox-private:latest", registryAuth);
//3、另一个实现的简单方法
// You can also set the RegistryAuth for the DockerClient instead of passing everytime you call pull()
DockerClient docker = DefaultDockerClient.fromEnv().registryAuth(registryAuth).build();


/**
*创建容器部分
*
/


// 绑定容器端口到主机端口:Bind container ports to host ports
final String[] ports = {"80", "22"};
final Map<String, List<PortBinding>> portBindings = new HashMap<>();
for (String port : ports) {
    List<PortBinding> hostPorts = new ArrayList<>();
    hostPorts.add(PortBinding.of("0.0.0.0", port));
    portBindings.put(port, hostPorts);
}


// 将容器端口443绑定到自动分配的可用主机端口:Bind container port 443 to an automatically allocated available host port.
List<PortBinding> randomPort = new ArrayList<>();
randomPort.add(PortBinding.randomPort("0.0.0.0"));
portBindings.put("443", randomPort);


final HostConfig hostConfig = HostConfig.builder().portBindings(portBindings).build();


// 创建具有暴露端口的容器:Create container with exposed ports
final ContainerConfig containerConfig = ContainerConfig.builder()
    .hostConfig(hostConfig)
    .image("busybox").exposedPorts(ports)
    .cmd("sh", "-c", "while :; do sleep 1; done")
    .build();


final ContainerCreation creation = docker.createContainer(containerConfig);
final String id = creation.id();


// 查健康度,获取容器的元数据:Inspect container
final ContainerInfo info = docker.inspectContainer(id);


// 开启容器:Start container
docker.startContainer(id);


//在运行的容器中执行attached和STDERR命令
// Exec command inside running container with attached STDOUT and STDERR
final String[] command = {"bash", "-c", "ls"};
final ExecCreation execCreation = docker.execCreate(
    id, command, DockerClient.ExecCreateParam.attachStdout(),
    DockerClient.ExecCreateParam.attachStderr());
final LogStream output = docker.execStart(execCreation.id());
final String execOutput = output.readFully();


// 杀掉一个运行中的容器。:Kill container
docker.killContainer(id);


// 删除一个容器:Remove container
docker.removeContainer(id);


// 关闭一个容器:Close the docker client
docker.close();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值