部署为 Docker 映像时如何运行多个 lambda 函数?

问题描述

dockerfile 中声明多个函数/应用程序时,通过 aws-sam 使用 docker 映像的 aws lambda 的 templates.yaml 看起来如何?

这是运行“单个应用”的示例 dockerfile

FROM public.ecr.aws/lambda/python:3.8

copY app.py requirements.txt ./

RUN python3.8 -m pip install -r requirements.txt -t .

# Command can be overwritten by providing a different command in the template directly.
CMD ["app.lambda_handler"]

解决方法

Dockerfile 本身看起来是一样的。无需更改。

Docker 文件中的 CMD 行看起来需要更改,但这是误导性的。 CMD 值可以在 template.yaml 文件中按函数指定。

必须使用有关新函数的信息更新 template.yaml 文件。您需要为每个函数添加一个 ImageConfig 属性。 ImageConfig 属性必须以与 CMD 值相同的方式指定函数的名称,否则会这样做。

您还需要将每个函数的 DockerTag 值更新为唯一的,尽管此 may be a bug 是。

这是 NodeJs“Hello World”示例模板。yaml 的资源部分,更新为支持单个 Docker 映像的多个功能:

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      ImageConfig:
        Command: [ "app.lambdaHandler" ]
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
    Metadata:
      DockerTag: nodejs14.x-v1-1
      DockerContext: ./hello-world
      Dockerfile: Dockerfile
  HelloWorldFunction2:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      ImageConfig:
        Command: [ "app.lambdaHandler2" ]
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello2
            Method: get
    Metadata:
      DockerTag: nodejs14.x-v1-2
      DockerContext: ./hello-world
      Dockerfile: Dockerfile

这假设 app.js 文件已被修改为提供 exports.lambdaHandlerexports.lambdaHandler2。我假设相应的python文件也应该类似修改。

以这种方式更新 template.yaml 后,sam local start-api 按预期工作,将 /hello 路由到 lambdaHandler,将 /hello2 路由到 lambdaHandler2。>

这在技术上创建了两个单独的 Docker 镜像(每个不同的 DockerTag 值一个)。但是,除了标记之外,这两个图像将是相同的,并且基于相同的 Dockerfile,因此第二个图像将使用第一个图像的 Docker 缓存。