使用 Docker CLI 创建容器映像,然后使用 Lambda 控制台从容器映像创建函数。
- linux 机器
- 安装有 aws cli
- 安装有 docker
- 安装有 nodejs
mkdir lambda-docker
cd lambda-docker/
vim app.js
app.js
exports.handler = async (event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
FROM public.ecr.aws/lambda/nodejs:12
# Copy function code and package.json
COPY app.js package.json /var/task/
# Install NPM dependencies for function
RUN npm install
# Set the CMD to your handler
CMD [ "app.handler" ]
vim package.json
npm init
docker build -t hello-world .
- 运行 docker image
docker run -p 9000:8080 hello-world:latest
- 测试 lambda 函数。在新的terminal,运行以下命令
curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{}'
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 875593617141.dkr.ecr.us-east-1.amazonaws.com
aws ecr create-repository --repository-name hello-world --image-scanning-configuration scanOnPush=true --image-tag-mutability MUTABLE
docker tag hello-world:latest 875593617141.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest
docker push 875593617141.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest
确保创建函数的 role 有如下 policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ecr:SetRepositoryPolicy",
"ecr:GetRepositoryPolicy"
],
"Resource": "arn:aws:ecr:us-east-1:875593617141:repository/hello-world"
}
]
}
- 函数名称: DockerLambdaForShayne
- container image URI: 875593617141.dkr.ecr.us-east-1.amazonaws.com/hello-world:latest
在 Test 选项下,点击 Invoke。
可以看到执行结果。