2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Lambda関数でDockerコンテナ化されたPythonのFastAPIサービスを動かす

Posted at

Lambda関数でDockerコンテナ化されたPythonのFastAPIサービスを動かす

ディレクトリを作成する

docker -v
mkdir lambda_fastapi
cd lambda_fastapi

fastAPIサービスを実装する

touch app.py
  • ~/aws/lambda_fastapi/app.py
from fastapi import FastAPI
from pydantic import BaseModel
from mangum import Mangum

class Item(BaseModel):
    name: str
    price: float

app = FastAPI()

@app.get('/')
async def root():
  return {"message": "Hello from lambda"}

@app.get("/uppercase")
async def uppercase(text: str):
    return {"message": text.upper()}

@app.post("/items")
async def create_item(item: Item):
    return item

handler = Mangum(app)

ライブラリ記述ファイルを作る

touch requirements.txt
  • ~/aws/lambda_fastapi/requirements.txt
fastapi
mangum

Dockerfileを作る

touch Dockerfile
  • ~/aws/lambda_fastapi/Dockerfile
FROM public.ecr.aws/lambda/python:3.12

COPY app.py ${LAMBDA_TASK_ROOT}
COPY requirements.txt ${LAMBDA_TASK_ROOT}

RUN pip install -r ./requirements.txt

CMD ["app.handler"]

Dockerイメージをビルドする

docker build -t lambda_fastapi .
docker images

動作確認する

docker run -p 9000:8080 lambda_fastapi
docker ps

サービスを確認する

  • GETリクエスト
curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{"resource": "/", "path": "/", "httpMethod": "GET", "requestContext": {}}'
  • POSTリクエスト
curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" \
-d '{
  "resource": "/items",
  "path": "/items",
  "httpMethod": "POST",
  "requestContext": {},
  "body": "{\"name\": \"Keyboard\",\"price\":10000}"
}'

ECRリポジトリの作成

  • AWSのprodプロファイルに切り替え
aws ecr ls --profile prod
export AWS_PROFILE=prod
  • 認証トークンを取得し、レジストリに対して Docker クライアントを認証
aws ecr get-login-password --region ap-northeast-1 --profile prod | docker login --username AWS --password-stdin 11111111111111111.dkr.ecr.ap-northeast-1.amazonaws.com
  • ECRリポジトリの作成
aws ecr create-repository --repository-name lambda_fastapi_repo --profile prod --image-scanning-configuration scanOnPush=true --image-tag-mutability MUTABLE
  • Dockerイメージをタグ付け
docker tag lambda_fastapi:latest 11111111111111111.dkr.ecr.ap-northeast-1.amazonaws.com/lambda_fastapi_repo:latest
docker images
  • 実行結果
REPOSITORY                                                              TAG       IMAGE ID       CREATED          SIZE
11111111111111111.dkr.ecr.ap-northeast-1.amazonaws.com/lambda_fastapi_repo   latest    ee65f52d4fed   44 minutes ago   543MB
lambda_fastapi                                                          latest    ee65f52d4fed   44 minutes ago   543MB
  • イメージのアップロード
docker push 11111111111111111.dkr.ecr.ap-northeast-1.amazonaws.com/lambda_fastapi_repo:latest
  • 実行結果
The push refers to repository [211125541523.dkr.ecr.ap-northeast-1.amazonaws.com/lambda_fastapi_repo]
3dded92ad458: Pushed 
・・・・省略・・・・
922a9a710c9e: Pushed 
latest: digest: sha256:dkspdksokoskodksokdoskodskodksodksokdosa size: 2203
  • リポジトリ情報の確認
aws ecr describe-repositories
  • 実行結果
{
  "repositoryArn": "arn:aws:ecr:ap-northeast-1:11111111111111111:repository/lambda_fastapi_repo",
  "registryId": "11111111111111111",
  "repositoryName": "lambda_fastapi_repo",
  "repositoryUri": "11111111111111111.dkr.ecr.ap-northeast-1.amazonaws.com/lambda_fastapi_repo",
  "createdAt": "2024-03-30T10:42:52.223000+09:00",
  "imageTagMutability": "MUTABLE",
  "imageScanningConfiguration": {
      "scanOnPush": true
  },
  "encryptionConfiguration": {
      "encryptionType": "AES256"
  }
}

Lambda関数の作成

関数URLの設定

関数URLの確認

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?