0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Dockerfileについてしデプロイする

Posted at

FastAPI + CodeCommit + Docker + Fargate の構成ですね。
このパターン、AWSのマイクロサービス構築にすごく相性いいです。
以下の流れで進めればバッチリです!


✅ 全体の流れ(ざっくり)

  1. CodeCommit からクローン
  2. Dockerfile 作成
  3. ECR に Docker イメージを push
  4. ECS(Fargate)タスク定義を作成
  5. サービス or タスクを起動

① CodeCommitからプロジェクトを取得

EC2やローカルで作業中なら:

git clone https://git-codecommit.ap-northeast-1.amazonaws.com/v1/repos/your-fastapi-repo
cd your-fastapi-repo

※ HTTPSの認証には AWS CLI の認証情報が必要(aws configure済みであること)


② Dockerfile をプロジェクトに追加

プロジェクトのルートに以下の Dockerfile を置きます:

FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .

RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]

main:appmain.py にある app = FastAPI() を指します。適宜ファイル名を変えてください。


③ ECRにイメージをpush

# ECRログイン
aws ecr get-login-password --region ap-northeast-1 | \
  docker login --username AWS --password-stdin <AWSアカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com

# リポジトリ作成(初回だけ)
aws ecr create-repository --repository-name fastapi-app

# イメージビルドとタグ付け
docker build -t fastapi-app .
docker tag fastapi-app:latest <アカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com/fastapi-app:latest

# プッシュ
docker push <アカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com/fastapi-app:latest

④ Fargate用ECSタスク定義を作成

AWSコンソール or CLI / CloudFormation / Terraform で定義できます。

最低限必要な設定:

  • タスク名、メモリ、CPU
  • 実行ロール(ecsTaskExecutionRole
  • コンテナ → ECRのイメージURI
  • ポートマッピング(例:80)

⑤ ECSサービス or タスクを作成して起動

  • Webアプリとして継続稼働 → ECSサービス
  • 一時的なAPIやジョブ → 単発タスク

🎁 おまけ: requirements.txt

fastapi
uvicorn[standard]

必要に応じて SQLAlchemy や boto3 など追加できます。


必要であれば…

  • ECSタスク定義のテンプレート(JSON/CloudFormation)
  • CodePipelineでCodeCommit → Build → DeployのCI/CD構成
  • ALB経由でFastAPIを公開する構成

了解です!
では、CodeCommit の FastAPI プロジェクトを Fargate に自動デプロイ(CI/CD)し、ALB 経由で公開する構成を、以下の手順でフルセットアップしていきますね。


🎯 ゴール:構成図(簡略)

Developer (push)
    ↓
AWS CodeCommit(FastAPIコード)
    ↓
CodePipeline
  - CodeBuild(Docker Build → ECR Push)
  - ECS Deploy(Fargateタスク更新)
    ↓
ECS (Fargate)
    ↓
ALB(ポート80/443 → FastAPI)

✅ ステップバイステップ


🔹 Step 1: CodeCommit で FastAPI プロジェクトを準備

すでに CodeCommit にプロジェクトがあるとのことなので、このステップはOKです。
Dockerfilerequirements.txt がリポジトリにあることを確認してください。

🔖 例:Dockerfile

FROM python:3.11-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]

🔹 Step 2: ECR にリポジトリを作成

aws ecr create-repository --repository-name fastapi-app

出力されるリポジトリURIをメモ:
例)<アカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com/fastapi-app


🔹 Step 3: ECS クラスターとサービスを作成(Fargate)

ここではマネジメントコンソールまたは CloudFormation / Terraform で構成できますが、まずは構成要素を整理します。

必要なもの:

  • ECSクラスター名fastapi-cluster
  • サービス名fastapi-service
  • タスク定義名fastapi-task
  • ポートマッピング:80
  • ECSタスク実行ロールecsTaskExecutionRole(マネージドポリシー付き)

タスク定義の JSON テンプレート(例)

{
  "family": "fastapi-task",
  "networkMode": "awsvpc",
  "requiresCompatibilities": ["FARGATE"],
  "cpu": "256",
  "memory": "512",
  "executionRoleArn": "arn:aws:iam::<アカウントID>:role/ecsTaskExecutionRole",
  "containerDefinitions": [
    {
      "name": "fastapi",
      "image": "<ECRリポジトリURI>:latest",
      "portMappings": [
        {
          "containerPort": 80,
          "protocol": "tcp"
        }
      ],
      "essential": true
    }
  ]
}

🔹 Step 4: ALB(Application Load Balancer)を作成

必要な構成:

  • ターゲットグループ(Fargateタスクを登録)
  • リスナー:ポート80(または443)
  • ALBセキュリティグループ:ポート80/443を許可
  • タスクのセキュリティグループ:ALBからのアクセスを許可

🔹 Step 5: CodeBuild の設定

buildspec.yml(プロジェクトルートに追加)

version: 0.2

phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws ecr get-login-password --region ap-northeast-1 | docker login --username AWS --password-stdin <アカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com
      - IMAGE_URI=<アカウントID>.dkr.ecr.ap-northeast-1.amazonaws.com/fastapi-app:latest
  build:
    commands:
      - echo Build started on `date`
      - docker build -t $IMAGE_URI .
      - docker push $IMAGE_URI
  post_build:
    commands:
      - echo Writing image definition file...
      - printf '[{"name":"fastapi","imageUri":"%s"}]' $IMAGE_URI > imagedefinitions.json

artifacts:
  files:
    - imagedefinitions.json

🔹 Step 6: CodePipeline の構成

ステージ構成:

  1. Source:CodeCommit
  2. Build:CodeBuild(上記 buildspec)
  3. Deploy:ECS(Fargate)

※ 最後のステージで、ECSの「サービス名」「クラスター名」「imagedefinitions.json」を使ってイメージ更新を自動反映。


🔹 Step 7: 確認・公開

  • CodeCommit に push → 自動で CodePipeline が発火
  • イメージが ECR に push
  • ECS のタスクが更新されて Fargate で実行
  • ALB 経由で FastAPI アプリにアクセスできる 🎉

🔧 補足:便利なオプション

  • Route53 で独自ドメインをALBに紐付け
  • ACMでSSL証明書(HTTPS対応)
  • CloudWatch Logs でログ確認
  • 環境変数やSecrets Manager連携で設定管理

🎁 必要に応じて

  • Terraform版構成(IaC)
  • CloudFormationテンプレート一式
  • HTTPS/ドメイン設定
  • 複数環境(dev/stg/prod)対応

どの部分から実装したいですか?
「今すぐ動かしたい!」場合は、まず buildspec.ymlDockerfile を揃えて、ECRとECS構成を一緒に固めましょうか?
TerraformやCloudFormationで全部自動化する方法もご希望なら、すぐ用意できます!

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?