使用spotify-docker-client创建容器配置内存提示最小6MB错误如何解决
错误根因
docker API中内存限制参数的单位是字节,你当前传入的memory参数值(比如示例的500)实际是500字节,远低于docker要求的最低6MB(即6291456字节)阈值,因此触发报错。
修复方案
- 补充单位换算逻辑
你可以默认约定前端传入的memory参数单位为MB,在传入配置前先换算为字节:
// 内存单位换算:MB -> 字节 Long memoryInByte = memory * 1024 * 1024; final HostConfig hostConfig = HostConfig.builder() .portBindings(portBindings) .cpuShares(cpu) .memory(memoryInByte) .build();
- 增加前置参数校验
提前校验内存阈值,避免请求直接发往docker服务触发报错:
final long MIN_ALLOWED_MEMORY = 6 * 1024 * 1024; // docker要求的最低内存,单位字节 if (memoryInByte < MIN_ALLOWED_MEMORY) { throw new IllegalArgumentException("容器内存配置最低不能小于6MB"); }
- 修复端口配置逻辑
你现有代码的端口绑定逻辑存在错误,exposedPorts仅需要填容器端口,端口绑定的key为容器端口/协议,修改后参考如下:
// 正确端口配置 String containerPortWithProtocol = containerPort + "/tcp"; Map<String, List<PortBinding>> portBindings = new HashMap<>(); portBindings.put(containerPortWithProtocol, List.of(PortBinding.of("0.0.0.0", hostPort))); final HostConfig hostConfig = HostConfig.builder() .portBindings(portBindings) .cpuShares(cpu) .memory(memoryInByte) .build(); final ContainerConfig containerConfig = ContainerConfig.builder() .hostConfig(hostConfig) .hostname(containerName) .image(imageName) .exposedPorts(containerPortWithProtocol) .build();
内容的提问来源于stack exchange,提问作者behrooz razzaghi
相关产品推荐
相关产品推荐

