You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Serverless Framework Python服务包过大致AWS Lambda CI/CD部署失败求助

解决Serverless Framework部署Lambda包体积超限问题

问题背景

本地部署Serverless服务可成功完成,但CI/CD流水线部署时触发以下报错:

UPDATE_FAILED: AzurePhishSimReportFunctionLambdaFunction (AWS::Lambda::Function)
Resource handler returned message: "Unzipped size must be smaller than 262144000 bytes (Service: Lambda, Status Code: 400, Request ID: 2b53c48c-adb8-45b8-8844-8bfb317612bb)" (RequestToken: 126200f8-fd75-9bd8-4c0e-6ebf4d0c4e40, HandlerErrorCode: InvalidRequest)

本地部署包仅16.58 MB,CI环境中却达136.71 MB,核心大依赖为botocore和cryptography,仅依赖requests、boto3、msal三个顶层依赖。已尝试serverless-python-requirements的zip/slim/layers功能、文件排除规则,但仍未解决,用Layers后主包仍有119.5 MB超限。

有效解决方法

1. 彻底清理CI环境的依赖缓存

CI环境可能残留旧依赖或完整编译包,需在安装依赖前强制清理:

# 清理pip缓存
pip cache purge
# 删除项目下的虚拟环境目录
rm -rf .venv/
# 删除serverless-python-requirements的缓存目录
rm -rf .serverless/requirements/

2. 精准配置serverless-python-requirements,结合slim与深度排除

在serverless.yml中优化插件配置,强制清理不必要的文件,同时排除Lambda运行时自带的依赖:

plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    slim: true  # 自动移除无用文件
    strip: true # 剥离调试符号
    noDeploy:
      - boto3  # 若使用Lambda运行时自带版本,直接排除
      - botocore
    exclude:
      - "**/*.pyc"
      - "**/__pycache__/**"
      - "**/*.dist-info/**"
      - "**/tests/**"
      - "**/docs/**"
      - "**/examples/**"
      - "cryptography/**/*.so" # 仅保留必要编译文件,或用Lambda层单独打包

3. 正确分离大依赖到Layers,避免主包重复打包

确保主包不再包含已放入Layer的依赖,同时Layer打包时只保留必要文件:

  • 单独创建Layer的requirements.txt,仅放入boto3、botocore、cryptography
  • 在serverless.yml中配置Layer并关联到函数:
layers:
  PythonDependencies:
    path: layers/python # 该目录下存放单独的requirements.txt
    compatibleRuntimes:
      - python3.11

functions:
  AzurePhishSimReportFunction:
    handler: handler.lambda_handler
    layers:
      - {Ref: PythonDependenciesLambdaLayer}

打包Layer时,同样启用slim和strip参数,确保Layer体积最小化。

4. 使用Lambda运行时自带的boto3版本

虽然AWS最佳实践提到自行打包,但如果体积压力大,可直接依赖Lambda运行时自带的boto3(需确认运行时版本匹配,比如Python 3.11自带boto3 1.28+),这样主包完全排除boto3和botocore,能大幅减少体积。

5. 手动裁剪cryptography依赖

cryptography包含大量编译后的二进制文件,可手动保留仅对应Lambda运行时架构(x86_64或arm64)的.so文件,删除其他架构的文件,进一步压缩体积。

内容的提问来源于stack exchange,提问作者createchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 08:57:32