如何將容器映像與 Lambda 搭配使用?

2 分的閱讀內容
0

我想要建立具有相依性的 AWS Lambda 容器映像。我該怎麼做?

解決方案

確認您已為建立 Lambda 容器映像的 IAM 使用者或角色設定許可。然後,請按照以下步驟使用 Docker 部署容器映像:

1.    前往「取得 Docker」網頁。選擇符合您要求的 Docker Desktop 應用程式。按照提供的說明安裝 Docker Desktop。
注意:Docker 是一個第三方網站。

2.    在您的本機電腦上,建立包含三個檔案的資料夾:Dockerfile、帶有程式庫的 requirements.txt 和帶有匯入陳述式的 app.py注意:使用最新版本的 Python for 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 執行階段介面模擬器 (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 年前