はじめに
AWS Lambdaをローカルでデバックしたい場面があり、その時に「docker-lambda」を使ってたのでその使い方をこの記事にまとめておきます。
docker-lambdaとは
AWS Lambdaをローカルでほぼ同様に再現するためのサンドボックスです。
A sandboxed local environment that replicates the live AWS Lambda environment almost identically – including installed software and libraries, file structure and permissions, environment variables, context objects and behaviors – even the user and running process are the same.
引用:「docker-lambda」
https://github.com/lambci/docker-lambda
docker-lambdaを使用する方法
まず初めに今回のデモで使用するLambdaに設定するアプリケーションコードを用意します。
// handler.js
exports.handler = async (event, context) => {
console.log(event)
console.log(context)
return "done"
}
今回は上の関数をAPIサーバーとして使用したいので、APIモードで起動します。APIモードで起動したい場合はDocker環境変数にDOCKER_LAMBDA_STAY_OPEN=1
を設定すれば良いです。
$ docker run --rm \
-e DOCKER_LAMBDA_STAY_OPEN=1 \
-p 9001:9001 \
-v $PWD:/var/task:ro,delegated \
lambci/lambda:nodejs12.x \
./handler.handler
こうすることでLambda API listening on port 9001...
といった標準出力が吐き出され、APIモードでLambda関数を立ち上げることができます。ここLambda Invork APIと呼ばれるAPIと一緒にHTTPリクエストを送信することで、Lambda関数を叩くことができます。
https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html
次のcurlを実行するとLambda関数が返すレスポンスが返ってきます。
$ curl -d '{}' http://localhost:9001/2015-03-31/functions/function/invocations
"done"
第1引数のeventに値を渡したい場合はbodyに値を設定すれば良いです。
curl -d '{"hoge":"value"}' http://localhost:9001/2015-03-31/functions/function/invocations
"done"
Lambda側の標準出力でeventに渡したobjectが格納されていることが確認できます。
2021-... 5d600b7b-8f7a-157f-... INFO { hoge: 'value' }
2021-... 5d600b7b-8f7a-157f-... INFO {
callbackWaitsForEmptyEventLoop: [Getter/Setter],
succeed: [Function],
fail: [Function],
done: [Function],
functionVersion: '$LATEST',
functionName: 'test',
memoryLimitInMB: '1536',
logGroupName: '/aws/lambda/test',
logStreamName: '2021/...',
clientContext: undefined,
identity: undefined,
invokedFunctionArn: 'arn:aws:lambda:us-east-1:148362654:function:test',
awsRequestId: '5d600b7b-8f7a-157f-e63c-...',
参考文献: