容器化AWS Python Lambda报错:No module named awslambdaric
解决Docker运行Lambda时"No module named awslambdaric"错误
问题场景
通过Docker容器运行AWS Python Lambda函数,CloudWatch报错:No module named awslambdaric。已尝试两种安装方式:Docker容器内直接执行安装命令、通过requirements.txt安装,但问题依旧。
相关配置
Dockerfile内容
FROM public.ecr.aws/lambda/python:3.10 ENTRYPOINT ["/var/runtime/custom_entrypoint"] exec env ALL_PROXY="socks5://localhost:1055/" /var/lang/bin/python3.10 -m awslambdaric $@
安装命令
RUN pip install -r requirements.txt RUN pip install awslambdaric
requirements.txt内容
isodate~=0.6.0 pydantic~=1.10.4 typing-extensions~=4.10.0 urllib3 pysocks awslambdaric ask_sdk_core ask_sdk_model
CloudWatch错误日志
2024-04-24T08:18:02.922+02:00 /var/lang/bin/python3.10: No module named awslambdaric 2024-04-24T08:18:03.039+02:00 INIT_REPORT Init Duration: 1754.90 ms Phase: invoke Status: error Error Type: Runtime.ExitError 2024-04-24T08:18:03.039+02:00 START RequestId: 1a5a7764-5e5f-4692-8883-5e065c87c536 Version: $LATEST 2024-04-24T08:18:03.060+02:00 RequestId: 1a5a7764-5e5f-4692-8883-5e065c87c536 Error: Runtime exited with error: exit status 1 Runtime.ExitError 2024-04-24T08:18:03.060+02:00 END RequestId: 1a5a7764-5e5f-4692-8883-5e065c87c536 2024-04-24T08:18:03.060+02:00 REPORT RequestId: 1a5a7764-5e5f-4692-8883-5e065c87c536 Duration: 1775.85 ms Billed Duration: 1776 ms Memory Size: 128 MB Max Memory Used: 18 MB
解决方案
1. 强制使用Lambda镜像的Python环境安装模块
Lambda官方Python镜像的默认Python路径为/var/lang/bin/python3.10,直接使用pip可能会安装到非目标环境。修改Dockerfile中的安装命令,指定使用目标Python的pip:
RUN /var/lang/bin/python3.10 -m pip install -r requirements.txt RUN /var/lang/bin/python3.10 -m pip install awslambdaric
2. 修复ENTRYPOINT配置格式错误
原Dockerfile中ENTRYPOINT与exec命令的写法不符合容器规范,需将代理逻辑写入独立的entrypoint脚本:
- 创建
custom_entrypoint.sh脚本:
#!/bin/sh exec env ALL_PROXY="socks5://localhost:1055/" /var/lang/bin/python3.10 -m awslambdaric "$@"
- 修改Dockerfile,复制并赋予脚本执行权限:
FROM public.ecr.aws/lambda/python:3.10 COPY custom_entrypoint.sh /var/runtime/custom_entrypoint RUN chmod +x /var/runtime/custom_entrypoint RUN /var/lang/bin/python3.10 -m pip install -r requirements.txt ENTRYPOINT ["/var/runtime/custom_entrypoint"]
3. 验证模块安装状态
构建镜像后,运行容器进入交互式模式,检查模块是否存在:
docker run -it --rm <你的镜像名称> /bin/bash /var/lang/bin/python3.10 -c "import awslambdaric; print('模块已找到')"
若输出模块已找到,说明安装成功。
4. 排查代理对安装的影响
如果代理配置异常,可能导致模块未成功下载。可在安装时临时关闭代理:
RUN unset ALL_PROXY && /var/lang/bin/python3.10 -m pip install -r requirements.txt
内容的提问来源于stack exchange,提问作者MelleD
相关产品推荐
相关产品推荐

