需求

之前工作流的运行都是用的docker-java提供的api拉起的docker容器直接跑服务,但是最新线上的新业务资源消耗较大,单个容器如果不加控制,CPU和内存都会拉满,导致服务器莫名宕机事故的发生,所以Docker限制cpu使用率和内存限制就得安排上

实施

HostConfig构建

自定义HostConfig,设置cpu和内存限制,pipeline配置了就按照配置来,如果没有就走默认配置

public void setUp() {
this.dockerHostConfig = new HostConfig();
Double memoryValue = this.pipeline.getMemory() != null
? this.pipeline.getMemory() * 1024 * 1024 * 1024
: this.config.getDefaultMemoryLimitInGb() * 1024 * 1024 * 1024;
this.dockerHostConfig.withMemory(memoryValue.longValue()); double cpu = StringUtils.isNotBlank(this.pipeline.getCpu())
? Double.parseDouble(this.pipeline.getCpu())
: this.config.getDefaultCpuCoreLimit();
// 单个 CPU 为 1024,两个为 2048,以此类推
this.dockerHostConfig.withCpuShares((int)(cpu * 1024));
}

CreateContainerCmd 构建

public String startContainer(String image,
String name,
List<ContainerPortBind> portBinds,
List<ContainerVolumeBind> volumeBinds,
List<String> extraHosts,
List<String> envs,
List<String> entrypoints,
HostConfig hostConfig,
String... cmds) {
List<Volume> volumes = new ArrayList<>();
List<Bind> volumesBinds = new ArrayList<>(); ……
……
…… CreateContainerCmd cmd = this.client.createContainerCmd(image)
.withName(name)
.withVolumes(volumes)
.withBinds(volumesBinds); if (portBinds != null && portBinds.size() > 0) {
cmd = cmd.withPortBindings(portBindings);
} if (cmds != null && cmds.length > 0) {
cmd = cmd.withCmd(cmds);
} if (extraHosts != null && extraHosts.size() > 0) {
cmd.withExtraHosts(extraHosts);
} if (envs != null) {
cmd.withEnv(envs);
} if (entrypoints != null) {
cmd.withEntrypoint(entrypoints);
} // 这一句是重点
cmd.withHostConfig(hostConfig); CreateContainerResponse container = cmd.exec();
this.client.startContainerCmd(container.getId()).exec();
return container.getId();
}

docker inspect containerId

执行 docker inspect a436678ccb0c 结果如下

"HostConfig": {
"Binds": [],
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {
"max-file": "3",
"max-size": "10m"
}
},
"NetworkMode": "default",
"PortBindings": null,
"RestartPolicy": {
"Name": "",
"MaximumRetryCount": 0
}
"CpuShares": 2048,
"Memory": 6442450944,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": null
}

CpuShares和Memory已经是我们设置的默认值,API生效,我们再来看下执行的日志

proc "pipeline_task_4b86c7830e4c4e39a77c454589c9e7e9_1" starting 2021-09-22 17:30:15 logPath:/mnt/xx/xx/logs/2021/09/22/bfbadf65-ac41-459d-a96d-3dc9a0105c25/job.log
+ java -jar /datavolume/xxx/xx.jar --spring.profiles.active=test
STDERR: Error: Unable to access jarfile /datavolume/xxx/xx.jar
5c494aeacb87af3a46a4fedc6e695ae888d4d2b9d7e603f24ef7fe114956c782 finished!
proc "pipeline_task_4b86c7830e4c4e39a77c454589c9e7e9_1" exited with status 1
proc "新增节点" error
start to kill all pipeline task
pipeline exit with error

执行文件没有找到,向上看Binds为空,所以挂载丢了,可以为什么了?明明 withVolumes()withBinds() 两个方法逻辑都没有动,还是看下源码分析一下吧

问题定位与解决

看源码之前我们先了解一下docker的hostConfig,文件路径在:/var/lib/docker/containers//hostconfig.json

其实这个就是容器运行的宿主机配置,磁盘绑定,cpu、内存限制、DNS、网络以及种种配置都在这个文件中,docker-java中HostConfig对象其实就是这个json对应的model,我们自定义了HostConfig对象,问题应当是出在 cmd.withHostConfig(hostConfig); 这一句代码上

以前的绑定逻辑

之前没有限制,所以在实例化CreateContainerCmd时候没有定制HostConfig参数

CreateContainerCmd cmd = this.client.createContainerCmd(image)
.withName(name)
.withVolumes(volumes)
.withBinds(volumesBinds);

CreateContainerCmd withBinds

/**
*
* @deprecated see {@link #getHostConfig()}
*/
@Deprecated
default CreateContainerCmd withBinds(Bind... binds) {
Objects.requireNonNull(binds, "binds was not specified");
getHostConfig().setBinds(binds);
return this;
}

getHostConfig() 方法追溯到实现类 CreateContainerCmdImpl hostConfig是直接在类实例化的时候new出来的一个新对象

@JsonProperty("HostConfig")
private HostConfig hostConfig = new HostConfig();

我们再看下 CreateContainerCmdwithHostConfig() 方法,代码也是在实现类里面

@Override
public CreateContainerCmd withHostConfig(HostConfig hostConfig) {
this.hostConfig = hostConfig;
return this;
}

直接覆盖了对象中原来的hostConfig, 我们的withHostConfig又在最后调用的可不就把挂载丢了吗,正好CreateContainerCmd 的 withBinds 方法也被 @Deprecated 修饰了,我们就来调整一下代码

public String startContainer(String image,
String name,
List<ContainerPortBind> portBinds,
List<ContainerVolumeBind> volumeBinds,
List<String> extraHosts,
List<String> envs,
List<String> entrypoints,
HostConfig hostConfig,
String... cmds) {
List<Volume> volumes = new ArrayList<>();
List<Bind> volumesBinds = new ArrayList<>(); …… //这一行很关键
hostConfig.withBinds(volumesBinds); if (portBinds != null && portBinds.size() > 0) {
hostConfig.withPortBindings(portBindings);
} if (extraHosts != null && extraHosts.size() > 0) {
hostConfig.withExtraHosts(extraHosts.toArray(new String[extraHosts.size()]));
}
CreateContainerCmd cmd = this.client.createContainerCmd(image).withHostConfig(hostConfig)
.withName(name)
.withVolumes(volumes); if (cmds != null && cmds.length > 0) {
cmd = cmd.withCmd(cmds);
} if (envs != null) {
cmd.withEnv(envs);
} if (entrypoints != null) {
cmd.withEntrypoint(entrypoints);
} CreateContainerResponse container = cmd.exec();
this.client.startContainerCmd(container.getId()).exec();
return container.getId();
};

OK,搞定,docker stats 查看容器的cpu占用,始终不会超过200%

参考链接

https://github.com/docker-java/docker-java

Docker-Java限制cpu和内存及浅析源码解决docker磁盘挂载失效问题的更多相关文章

  1. 方法:Linux 下用JAVA获取CPU、内存、磁盘的系统资源信息

    CPU使用率: InputStream is = null; InputStreamReader isr = null; BufferedReader brStat = null; StringTok ...

  2. 如何使用 Docker 来限制 CPU、内存和 IO等资源?

    如何使用 Docker 来限制 CPU.内存和 IO等资源?http://www.sohu.com/a/165506573_609513

  3. Linux下使用java获取cpu、内存使用率

    原文地址:http://www.voidcn.com/article/p-yehrvmep-uo.html 思路如下:Linux系统中可以用top命令查看进程使用CPU和内存情况,通过Runtime类 ...

  4. java中的==、equals()、hashCode()源码分析(转载)

    在java编程或者面试中经常会遇到 == .equals()的比较.自己看了看源码,结合实际的编程总结一下. 1. ==  java中的==是比较两个对象在JVM中的地址.比较好理解.看下面的代码: ...

  5. Java的三种代理模式&完整源码分析

    Java的三种代理模式&完整源码分析 参考资料: 博客园-Java的三种代理模式 简书-JDK动态代理-超详细源码分析 [博客园-WeakCache缓存的实现机制](https://www.c ...

  6. Java 集合系列 09 HashMap详细介绍(源码解析)和使用示例

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  7. Java 集合系列 10 Hashtable详细介绍(源码解析)和使用示例

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  8. Java 集合系列 06 Stack详细介绍(源码解析)和使用示例

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

  9. Java 集合系列 05 Vector详细介绍(源码解析)和使用示例

    java 集合系列目录: Java 集合系列 01 总体框架 Java 集合系列 02 Collection架构 Java 集合系列 03 ArrayList详细介绍(源码解析)和使用示例 Java ...

随机推荐

  1. jsoup的Document类

    一.简介 Document是一个装载html的文档类,它是jsoup一个非常重要的类.类声明:public class Document extends Element .Document是Node间 ...

  2. Buffer和Cache的异同

    Buffer的本质是缓冲,常见实例如下面这个: 对,就是铁道端头那个巨大的弹簧一类的东西.作用是万一车没停住(是没停住啊,刹车了但是差一点没刹住那种,不是不拉刹直接撞上来),撞弹簧上减速降低危险,起到 ...

  3. rest operater剩余操作符

    rest叫做剩余操作符(rest operator),是解构的一种,意思就是把剩余的东西放到一个array里面赋值给它.一般只针对array的解构 //rest叫做剩余操作符(rest operato ...

  4. 利用元数据提高 SQLFlow 血缘分析结果准确率

    利用元数据提高 SQLFlow 血缘分析结果准确率 一.SQLFlow--数据治理专家的一把利器 数据血缘属于数据治理中的一个概念,是在数据溯源的过程中找到相关数据之间的联系,它是一个逻辑概念.数据治 ...

  5. 小程序 mpvue page "xxx" has not been registered yet

    新增了几个页面,改了下目录结构,就开始报这个错. 重启了几次不管用,google 一番也无果. 灵机一动试一下 build npm run build build 版本没报错,OK 然后 $ rm - ...

  6. 编程读写CAD文件验证

    背景 B/S应用系统,根据用户上传数据:业务数据和CAD坐标数据,经过一系列运筹算法运算后,输出一批坐标数据,作为给用户的规划结果.此时需要方便直观的给用户展示坐标数据.可选方式有两个: web页面画 ...

  7. K8S资源编排(yaml)

    1.yaml的格式 2.yaml的组成部分 3.yaml常用字段的含义 4.yaml编写方式 (1)方式一:使用kubectl create命令生成yaml文件,然后修改 (2)方式2:在已经部署好的 ...

  8. window创建l2tp

    windows上创建一个L2TP的隧道连接 进入控制面板,打开"网络和共享中心",如下图,之后点击"设置新的连接或网络" 进入到"设置连接或网络&qu ...

  9. Linux-实战常用命令

    目录 关机/重启/注销 系统信息和性能查看 磁盘和分区 ⽤户和⽤户组 ⽹络和进程管理 常⻅系统服务命令 ⽂件和⽬录操作 ⽂件查看和处理 打包和解压 RPM包管理命令 YUM包管理命令 DPKG包管理命 ...

  10. 【第九篇】- Git 标签之Spring Cloud直播商城 b2b2c电子商务技术总结

    Git 标签 如果你达到一个重要的阶段,并希望永远记住那个特别的提交快照,你可以使用 git tag 给它打上标签. 比如说,我们想为我们的 xxx 项目发布一个"1.0"版本. ...