Podman构建Rust代码时出现exit status 137失败,求解决方法
解决Podman跨平台构建Rust镜像时exit status 137错误的思路
问题背景
在darwin/arm64系统上使用Podman将某Rust项目容器化为linux/amd64平台镜像,构建过程中出现exit status 137错误。
使用的ContainerFile
FROM --platform=linux/amd64 rust:slim as cargo-build WORKDIR /usr/src/app RUN apt-get update RUN apt-get install build-essential libssl-dev openssl cmake -y COPY . . RUN cargo build --release FROM --platform=linux/amd64 ubuntu:latest RUN apt-get update RUN apt-get install ca-certificates libssl-dev openssl -y WORKDIR /src/app COPY .env . COPY --from=cargo-build /usr/src/app/target/release/bario-beck . ENV RUST_LOG=info EXPOSE 8080 # Run the application CMD ["./bario-beck"]
构建错误信息
[1/2] STEP 6/6: RUN cargo build --release Updating crates.io index Killed Error: building at STEP "RUN cargo build --release": while running runtime: exit status 137
已尝试的操作
- 将Podman机器的内存从1GB调整到8GB,CPU从1核调整到4核,问题依旧;
- 尝试用Docker构建,出现相同错误;
- 尝试为本机darwin/arm64平台构建,同样失败。
Podman机器配置
[ { "ConfigPath": { "Path": "~/.config/containers/podman/machine/qemu/podman-machine-default.json" }, "ConnectionInfo": { "PodmanSocket": { "Path": "~/.local/share/containers/podman/machine/qemu/podman.sock" }, "PodmanPipe": null }, "Created": "2023-05-28T14:55:24.150251-03:00", "Image": { "IgnitionFilePath": { "Path": "~/.config/containers/podman/machine/qemu/podman-machine-default.ign" }, "ImageStream": "testing", "ImagePath": { "Path": "~/.local/share/containers/podman/machine/qemu/podman-machine-default_fedora-coreos-38.20230514.2.0-qemu.aarch64.qcow2" } }, "LastUp": "2023-05-28T15:56:43.403634-03:00", "Name": "podman-machine-default", "Resources": { "CPUs": 4, "DiskSize": 100, "Memory": 8192 }, "SSHConfig": { "IdentityPath": "~/.ssh/podman-machine-default", "Port": 51641, "RemoteUsername": "core" }, "State": "running" } ]
解决思路
1. 优化Cargo构建缓存,降低内存占用
通过分层缓存依赖,避免每次构建都重新下载编译全部依赖,减少内存消耗。修改构建阶段的ContainerFile:
FROM --platform=linux/amd64 rust:slim as cargo-build WORKDIR /usr/src/app RUN apt-get update && apt-get install build-essential libssl-dev openssl cmake -y # 先复制依赖配置文件,缓存依赖层 COPY Cargo.toml Cargo.lock ./ # 创建临时源码触发依赖编译 RUN mkdir src && echo "fn main() {}" > src/main.rs RUN cargo build --release # 删除临时源码 RUN rm -rf src # 复制实际源码 COPY src ./src # 重新构建项目 RUN cargo build --release
2. 限制Cargo并行编译线程数
Rust默认使用与CPU核心数一致的线程编译,高并行易导致内存过载。构建时设置CARGO_BUILD_JOBS环境变量减少线程数:
RUN CARGO_BUILD_JOBS=2 cargo build --release
3. 检查资源状态
- 用
htop/top查看宿主机内存使用,确保有足够空闲内存供Podman虚拟机使用; - 通过
podman machine ssh进入虚拟机,执行df -h检查磁盘空间是否充足; - 在虚拟机内执行
free -h确认内存是否真正分配到位。
4. 改用轻量化基础镜像
尝试使用rust:alpine替代rust:slim,Alpine镜像体积更小,内存占用更低,需调整依赖安装命令:
FROM --platform=linux/amd64 rust:alpine as cargo-build WORKDIR /usr/src/app RUN apk add --no-cache build-base openssl-dev cmake # 后续缓存和构建步骤同上
5. 排查项目依赖
使用cargo tree查看依赖树,排查是否存在重型依赖,尝试替换或移除不必要的依赖,降低构建时的内存压力。
内容的提问来源于stack exchange,提问作者Joao Pedro P.P
相关产品推荐
相关产品推荐

