仕様
- Rails 8.0.2
- API モード
- Ruby3.4.2
- PostgreSQL 16.6
- Aurora Serverless v2
ソースコード
- アプリケーション
- インフラコード(Terraform)
サンプルコードを用意したので、手っ取り早く進めたい方は上記を clone してください。
環境構築
アプリケーション
$ docker compose build
$ docker compose run --rm api bundle exec rails db:prepare
$ docker compose up
$ curl http://localhost:3000/api/v1/users
{
"users": [
{
"id": 1,
"name": "山田 太郎",
"email": "yamada_t@example.com"
},
{
"id": 2,
"name": "山田 花子",
"email": "yamada_h@example.com"
}
]
}
users 一覧のデータが返ってくれば OK です。
インフラコード(Terraform)
初期化
$ terrarom init
環境変数をセット
$ cp terraform.tfvars.example terraform.tfvars
db_name = "app_production"
db_username = "posgtres"
db_password = "xxxxxxxxxxx"
rails_secret_key_base = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx..."
※ db_password
や rails_secret_key_base
などは適宜設定してください。
デプロイ
環境構築が完了したらいよいよデプロイ開始です。
ECR リポジトリを作成
$ terraform apply --target=aws_ecr_repository.rails8_api_apprunner
Docker イメージを build & push
$ aws ecr get-login-password --region ap-northeast-1 | docker login --username AWS --password-stdin <aws_account_id>.dkr.ecr.ap-northeast-1.amazonaws.com
$ docker buildx build --no-cache --platform=linux/x86_64 -f Dockerfile.prd -t rails8-api-apprunner .
$ docker tag rails8-api-apprunner:latest <aws_account_id>.dkr.ecr.ap-northeast-1.amazonaws.com/rails8-api-apprunner:latest
$ docker push <aws_account_id>.dkr.ecr.ap-northeast-1.amazonaws.com/rails8-api-apprunner:latest
RDS を作成
$ terraform apply \
--target=aws_rds_cluster.aurora_pg \
--target=aws_rds_cluster_instance.aurora_pg_instance
残りのリソースを作成
$ terraform apply
Outputs:
app_runner_service_url = "xxxxxxxxxx.ap-northeast-1.awsapprunner.com"
pp_runner_vpc_connector_arn = ...
動作確認
「Outputs」にて出力された app_runner_service_url
を参考に curl コマンドでリクエストを送信してみます。
$ curl https://xxxxxxxxxx.ap-northeast-1.awsapprunner.com/api/v1/users
{
"users": [
{
"id": 1,
"name": "山田 太郎",
"email": "yamada_t@example.com"
},
{
"id": 2,
"name": "山田 花子",
"email": "yamada_h@example.com"
}
]
}
users 一覧のデータが返ってくればデプロイ成功です。
まとめ
普段は ECS を使って開発している事が多いのですが、App Runner は最低限の設定で動作するため、ちょっとした検証のための環境を作りたい際などは便利だと感じました。