跳至内容

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

2 分钟阅读
0

我想创建带有依赖项的 AWS Lambda 容器映像。

解决方法

验证您是否为创建 Lambda 容器映像的 AWS Identity and Access Management (IAM) 用户或角色配置了权限。然后,按照以下步骤使用 Docker 部署容器映像:

  1. 前往 Docker 网站上的 Get Docker(获取 Docker)页面。选择符合您需求的 Docker 桌面版应用程序。按照提供的说明安装 Docker 桌面版。

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

    以下示例 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 sysdef 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 .

    注意: 如果从 Amazon ECR 公共存储库拉取时遇到身份验证错误,请参阅 Amazon ECR Public troubleshooting(Amazon ECR 公开映像故障排除)。

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

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

    docker run -p 9000:8080 hello-world
  5. 使用 GitHub 网站上 AWS 提供的 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 区域更改为您的账户 ID 和区域。

    以下是对 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 区域更改为您的账户 ID 和区域。

    以下是 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 函数。有关更多信息,请参阅使用容器映像创建 Lambda 函数。

AWS 官方已更新 2 年前