试试这个
对于有同样问题的人。
在你的 Dockerfile 中
FROM public.ecr.aws/lambda/python:3.8
# app.py is the file where is your lambda function
COPY app.py ${LAMBDA_TASK_ROOT}
# Install the function's dependencies using file requirements.txt
# from your project folder.
# To configure the libraries you can check this link:
# https://note.nkmk.me/en/python-pip-install-requirements/
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)
# app => filename
# handler => the function name where the program starts
CMD [ "app.handler" ]
在您的 app.py 文件中
import json
import time
import os
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, context):
token = event["token"]
# HERE WHEREVER YOU WANT THIS IS JUST AN EXAMPLE
print("Use token: ",token)
print("Lambda function ARN:", context.invoked_function_arn)
print("CloudWatch log stream name:", context.log_stream_name)
print("CloudWatch log group name:", context.log_group_name)
print("Lambda Request ID:", context.aws_request_id)
print("Lambda function memory limits in MB:", context.memory_limit_in_mb)
# We have added a 1 second delay so you can see the time remaining in get_remaining_time_in_millis.
time.sleep(1)
print("Lambda time remaining in MS:", context.get_remaining_time_in_millis())
json_region = None
try:
json_region = os.environ['AWS_REGION']
except KeyError:
json_region = "LOCAL ENVIRONMENT"
else:
json_region = "REGION NOT FOUND"
logger.info('Use a the logger')
return {
'statusCode': 200,
"headers": {
"Content-Type": "application/json"
},
"body": json.dumps({
"Region ": json_region
})
}
运行 docker 命令
构建
docker build -t yourcontainername .
跑步
docker run -p 9000:8080 yourcontainername
使用 CLI 进行测试
curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{}'
注意:如果您使用的是 Windows,请使用 -d "{"""token""":"""mytoken"""}"
如果一切顺利,响应如下:
{"statusCode": 200, "headers": {"Content-Type": "application/json"}, "body": "{\"Region \": \"LOCAL ENVIRONMENT\"}"}
所以...
在您的情况下,问题在于您的 Dockerfile
应该是这样的:
FROM public.ecr.aws/lambda/python:3.8
COPY myfunction.py ${LAMBDA_TASK_ROOT}
COPY requirements.txt .
RUN pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"
CMD ["myfunction.lambda_handler"]
根据文档
在函数处理程序旁边的 ${LAMBDA_TASK_ROOT} 目录下安装任何依赖项,以确保 Lambda 运行时可以在调用函数时找到它们。
资源
https://docs.aws.amazon.com/lambda/latest/dg/python-image.html#python-image-clients
https://docs.aws.amazon.com/lambda/latest/dg/images-create.html