如何在 Lambda 中使用容器镜像?

2 分钟阅读
0

我想创建具有依赖关系的 AWS Lambda 容器镜像。该如何操作?

解决方法

确认您已为创建 Lambda 容器镜像的 IAM 用户或角色配置了权限。然后,按照以下步骤使用 Docker 部署容器镜像:

1.    转到获取 Docker 网页。选择符合您要求的 Docker Desktop 应用程序。按照提供的说明安装 Docker Desktop。
注意:Docker 是一个第三方网站。

2.    在本地机器上,创建一个包含三个文件的文件夹:Dockerfile、包含库的 requirements.txt 和包含导入语句的 app.py注意:使用最新版本的 Python 作为 Amazon Elastic Container Registry (Amazon ECR) 公共注册表。

这个例子 Dockerfile 使用 Python 3.8:

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

# Copy function code
COPY app.py ${LAMBDA_TASK_ROOT}

# Install the function's dependencies using file requirements.txt
# from your project folder.

COPY requirements.txt .
RUN pip3 install -r requirements.txt —target "${LAMBDA_TASK_ROOT}"

# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "app.handler" ]

此示例 app.py 文件包含一个示例导入语句:

import sys
def handler(event, context):
    return 'Hello from AWS Lambda using Python' + sys.version + '!'

3.    使用 docker build 命令和一个映像名称构建您的 Docker 映像。

这是一个带有 hello-world 示例的 docker build 命令:

docker build -t hello-world .

4.    使用 docker run 命令启动 Docker 映像。

这是一个带有 hello-world 示例的 docker run 命令:

docker run -p 9000:8080 hello-world

5.    使用 Lambda Runtime Interface Emulator (RIE) 测试您的应用程序。在新的终端窗口中,使用 curl 命令将事件发布到以下端点:

curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{}'

此命令调用在容器镜像中运行的函数,然后返回响应。

6.    在您的 Amazon ECR 注册表中验证 Docker CLI。在命令中更改账户 ID 和 AWS 区域,确保符合您的要求。

以下是向 Amazon ECR 注册表验证 Docker CLI 的示例:

aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com

7.    使用 create-repository 命令在 Amazon ECR 中创建一个存储库。

这是一个 create-repository 命令示例:

aws ecr create-repository --repository-name hello-world --image-scanning-configuration scanOnPush=true --image-tag-mutability MUTABLE

8.    使用 docker tag 命令标记您的镜像以匹配您的存储库名称。然后,使用 docker push 命令将镜像部署到 Amazon ECR。

更改这些命令中的账户 ID 和 AWS 区域,以确保满足您的要求。

以下是 docker tag 命令示例:

docker tag hello-world:latest 123456789012.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest

以下是 docker push 命令示例:

docker push 123456789012.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest

9.    在 Amazon ECR 容器注册表中使用您的容器映像,创建并运行 Lambda 函数。有关更多信息,请参阅创建函数


AWS 官方
AWS 官方已更新 1 年前