~ 突破天際 ~
我們可以使用 Container image 的部署方式來解除煩人的 package size 的限制,不過需要用到 AWS ECR 這個服務,這個服務是要另外計費的唷
主要步驟如下:
docker build --platform linux/amd64 -t marathon-docker-image:test .
,這裡因為筆者是用Apple M1 Macbook,有加上 --platform linux/amd64
參數避免有些 image 沒有 platform=linux/arm64 的版本,也可以先用 export DOCKER_DEFAULT_PLATFORM=linux/amd64
指令指定預設平台# Dockerfile
FROM public.ecr.aws/lambda/python:3.11
# Copy requirements.txt
COPY requirements.txt ${LAMBDA_TASK_ROOT}
# Copy function code
COPY lambda_function.py ${LAMBDA_TASK_ROOT}
# Install the specified packages
RUN pip install -r requirements.txt
# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "lambda_function.handler" ]
- 本機 Docker CLI 要先向 AWS ECR 驗證通過
- build 本地端 Dockerfile 並 tag
- 讓本地端 docker tag 與 AWS ECR RepositoryUri 產生關聯
- 最後 Push 這個 RepositoryUri
# Step 2: deploy image to AWS ECR
$ aws sts get-caller-identity --query "Account" --output text
output: <accoungId>
$ aws ecr get-login-password \
--region ap-northeast-1 \
| docker login --username AWS \
--password-stdin {AWS_ACCOUNT_ID}.dkr.ecr.ap-northeast-1.amazonaws.com
$ aws ecr create-repository \
--repository-name marathon-image-repository \
--image-scanning-configuration scanOnPush=true \
--image-tag-mutability MUTABLE
$ docker tag marathon-docker-image:test \
<accountId>.dkr.ecr.ap-northeast-1.amazonaws.com/marathon-image-repository:latest
$ docker push \
<accountId>.dkr.ecr.ap-northeast-1.amazonaws.com/marathon-image-repository:latest
# Step 3: create lambda function with ECR RespositoryUri
$ aws iam get-role --role-name marathon-lambda-ex
$ aws lambda create-function \
--function-name marathon-lambda-image-function \
--package-type Image \
--code ImageUri=<accountId>.dkr.ecr.ap-northeast-1.amazonaws.com/marathon-image-repository:latest \
--role arn:aws:iam::<accountId>:role/marathon-lambda-ex
# invoke
$ aws lambda invoke --function-name marathon-lambda-image-function response.json
# response.json
"Hello from AWS Lambda using Python3.11.4 (main, Aug 15 2023, 15:47:10) [GCC 7.3.1 20180712 (Red Hat 7.3.1-15)]!"
當然,Serverless 的東西怎麼少的了 limitation 呢? 所幸的是只有兩項
最後注意這個 ECR 是要收費的喔,免費空間為 500 MB()
https://docs.aws.amazon.com/lambda/latest/dg/python-image.html
https://gcore.com/learning/deploy-you-cpp-lambda-funtion-with-docker/
https://aws.amazon.com/tw/blogs/aws/new-for-aws-lambda-container-image-support/