使用 CDK 部署带有层的容器化 lambda

Deploy containerized lambda with layer using CDK

我正在从事一个 ML 项目,该项目利用 AWS Lambda 构建模型和生成预测。 Lambda 是用 python 编写的,并使用了多个 ML 库,例如 pandas、sklearn、numpy 和 scikit-learn。 这些 lambda 使用由 Lambda 层打包的共享代码。 我使用 AWS CDK 进行项目部署。 CDK 代码是用 TypeScript 写的,不要问我为什么混用 Python 和 Typescript,在这种情况下是不相关的。

由于 ML 库,包的大小(lambda 代码 + 层)超过了最大允许大小 250MB。

在 AWS 宣布支持容器化 lambda 后,我决定尝试一下以克服 250MB 的限制。但是,我没有找到任何适合我情况的好例子,所以我正在尝试自己构建它。

CDK 代码如下所示:

...
// Create a lambda layer from code
// Code is located in lambda-code/ml directory and it looks 
// like any Python package with main ML and DB connection functions
const mlLayer = new PythonLayerVersion(this, 'mlLayer', {
      entry: './lambda-code/ml/',
})
...
// Lambda function is specified like
const classifyTransactionLambda = new DockerImageFunction(this, 'classifyTransactionLambda', {      
      code: DockerImageCode.fromImageAsset('./lambda-code/classify'),      
      memorySize: 512,      
      layers: [mlLayer],
      tracing: Tracing.ACTIVE,
      environment: {
        BUCKET_NAME: mlModelsBucket.bucketName,
        ENV: env
      }
});
...

代码的结构如下所示:

分类中的 Dockerfile lambda:

# Use the python lambda image from AWS ECR
FROM public.ecr.aws/lambda/python:3.7

COPY requirements.txt ./

RUN pip3 install -r requirements.txt

COPY index.py ./

CMD ["index.classify_transaction_handler"]

当我 运行 cdk deploy 我收到以下错误:

This lambda function uses a runtime that is incompatible with this layer (FROM_IMAGE is not in [python3.7])

有人 运行 遇到过这样的问题吗?此错误是否意味着 mlLayer 版本与 lambda classifyTransactionLambda 不兼容?

任何帮助将不胜感激!

此时

Functions defined as container images do not support layers. When you build a container image, you can package your preferred runtimes and dependencies as a part of the image.

https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html

所以我修改了我的构建以在构建图像之前将所有 layer/library 代码复制到每个 lambda 函数。