Dockerで仮想lambda環境の構築

docker-composeファイルのテンプレート

version: '3'

services:
  app:
    build: .
    volumes:
      - .:/app
    ports:
      - 9000:8080
    networks:
      - external.group
networks:
  external.group:
    external: true

Dockerfileのテンプレート

FROM public.ecr.aws/lambda/python:3.9

COPY app/app.py ${LAMBDA_TASK_ROOT}

# requirements.txt を 追加
ADD requirements.txt .
# pipをアップデート
RUN pip install --upgrade pip
# requirements.txt からライブラリをinstall
RUN pip install -r requirements.txt
# ハンドラーを設定
CMD [ "app.handler" ] 

このファイルは、 docker-compse.yml と同階層に設置する。

requirements.txtファイルのテンプレート

初期時に取り込むライブラリはないため、記述の必要はない。ファイルが存在すればよい。

ハンドラーを作成

任意のフォルダを作成し、その中にハンドラー用のファイルを作成する。
ファイル名は何でもよい。拡張子は 「.py

作成したファイルには、下記のようにロジックを作成する。

def handler(event, context):
    return 'XXXXXXXXXXXXXX'

起動コマンドの実行

Dockerは下記のコマンドを使用して起動する。

docker-compose up -d --build

ハンドラーの実行確認

下記コマンドを使用して、エンドポイントへイベントをポストする。

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