M1 Mac上AWS SAM CLI构建Docker镜像失败求助
M1 Mac上AWS SAM CLI本地调用Lambda报502错误的解决方法
问题场景
- 在M1 Mac上按官方流程执行
sam init、cd sam-app、sam build、sam deploy --guided,未修改任何代码或yaml配置 - 本地API服务启动正常:
➜ sam-app sam local start-api Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET] You can now browse to the above endpoints to invoke your functions. You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template 2023-01-23 17:54:06 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit)
- 执行
curl http://localhost:3000/hello时返回502错误,核心问题是Docker镜像构建失败,执行命令/bin/sh -c mv /var/rapid/aws-lambda-rie-x86_64 /var/rapid/aws-lambda-rie && chmod +x /var/rapid/aws-lambda-rie返回非零退出码1 - 已尝试
docker run --rm --privileged multiarch/qemu-user-static --reset -p yes命令,无改善
解决方案
1. 强制使用arm64架构的Lambda镜像
M1 Mac为arm64架构,默认x86_64镜像的转译可能存在兼容性问题,直接指定arm64镜像即可解决:
- 修改
template.yaml中函数的Runtime为对应arm64版本,例如:- Python:将
python3.9改为python3.9-arm64 - Node.js:将
nodejs18.x改为nodejs18.x-arm64
- Python:将
- 或者在启动本地API时直接指定架构参数:
sam local start-api --use-container --architecture arm64
2. 清理SAM与Docker缓存
缓存的旧镜像或构建产物可能引发冲突,执行以下命令清理后重新尝试:
- 清理SAM构建缓存:
sam build --clean
- 清理Docker无用镜像、容器与缓存:
docker system prune -af
3. 手动替换ARM版本的Lambda RIE二进制文件
如果上述方法无效,可手动替换镜像中的RIE文件为arm64版本:
- 拉取对应语言的arm64基础镜像(以Python 3.9为例):
docker pull public.ecr.aws/lambda/python:3.9-arm64
- 启动临时容器进入交互模式:
docker run -it --name temp-rie public.ecr.aws/lambda/python:3.9-arm64 /bin/sh
- 在容器内下载并配置arm64版本的RIE:
curl -Lo /var/rapid/aws-lambda-rie https://github.com/aws/aws-lambda-runtime-interface-emulator/releases/latest/download/aws-lambda-rie-arm64 chmod +x /var/rapid/aws-lambda-rie
- 提交修改后的自定义镜像:
docker commit temp-rie public.ecr.aws/lambda/python:3.9-arm64-custom
- 清理临时容器:
docker stop temp-rie && docker rm temp-rie
- 修改
template.yaml中函数的ImageUri为自定义镜像名称,重新执行sam build与sam local start-api
4. 更新SAM CLI至最新版本
旧版本SAM CLI对M1架构的支持可能存在缺陷,执行更新(以brew安装为例):
brew upgrade aws-sam-cli
内容的提问来源于stack exchange,提问作者Mathis Van Eetvelde
相关产品推荐
相关产品推荐

