跳至內容

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

2 分的閱讀內容
0

我想建立包含相依項目的 AWS Lambda 容器映像檔。

解決方法

確認建立 Lambda 容器映像檔的 AWS Identity and Access Management (IAM) 使用者或角色已設定必要的權限。接著,依照以下步驟使用 Docker 部署容器映像檔:

  1. 前往 Docker 網站上的取得 Docker頁面。選擇符合您需求的 Docker Desktop 應用程式。依照頁面上的指示安裝 Docker Desktop。

  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 疑難排解。

  4. 使用 docker run 命令啟動 Docker 映像檔。

    以下是以「hello-world」為例的 docker run 命令:

    docker run -p 9000:8080 hello-world
  5. 使用 GitHub 網站上 AWS 提供的 Lambda 執行時期介面模擬器 (RIE) 測試應用程式。開啟新的終端視窗,執行 curl 命令,將事件傳送至以下端點:

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

    此命令會調用在容器映像檔中執行的函式,然後傳回回應。

  6. 對 Docker CLI 進行身分驗證,使其能夠存取您的 Amazon ECR 登錄檔。
    將命令中的帳戶 ID 和 AWS 區域替換為您自己的帳戶 ID 和區域。

    以下命令示範如何對 Docker CLI 進行身分驗證,使其能夠存取 Amazon ECR 登錄檔:

    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 年前