はなちるのマイノート

Unityをメインとした技術ブログ。自分らしくまったりやっていきたいと思いますー!

【C#】minimal API(ASP.NET Core + .NET 8)で構築した最小構成のウェブサーバーをCloud Runで動作させる

はじめに

今回はminimal API(ASP.NET Core + .NET 8)で構築した最小構成のウェブサーバーをCloud Runで動作させる方法を書いていきます。

プロジェクトを作成する

まずはminimal APIを利用したプロジェクトを作成します。テンプレートがプレインストールされているので、それを利用してプロジェクトを作成します。

$ dotnet new web -o CloudRunSample -f net8.0
テンプレート "ASP.NET Core (空)" が正常に作成されました。

作成後の操作を処理しています...
C:\Users\-----\Desktop\CloudRunSample\CloudRunSample.csproj を復元しています:
  復元対象のプロジェクトを決定しています...
  C:\Users\-----\Desktop\CloudRunSample\CloudRunSample.csproj を復元しました (36 ms)。
正常に復元されました。

無事実行できると、以下のようなファイル群が生成されているはずです。

<project_folder>
│  appsettings.Development.json
│  appsettings.json
│  CloudRunSample.csproj
│  Program.cs
│
├─bin
├─obj
└─Properties
        launchSettings.json

重要なのはCloudRunSample.csprojProgram.csですね。

CloudRunSample.csprojnet8.0を利用していることを確認できます。

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>

Program.csでウェブサーバーを構築するコードを書きます。

var builder = WebApplication.CreateBuilder(args);

// PORT という環境変数が設定されていればそれを利用し、されていなければ 8080 をポートに利用する
var port = Environment.GetEnvironmentVariable("PORT") ?? "8080";

// 0.0.0.0 にする理由 : https://zenn.dev/shake_sanma/articles/1c6475ba73da48
var url = $"http://0.0.0.0:{port}";

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run(url);

Dockerfileについて

Dockerの環境を整えるためには例えば以下のようなDockerfileが必要です。

# .NET SDKのImage(https://mcr.microsoft.com/product/dotnet/sdk/about)を指定, .NET CLI + .NET runtime + ASP.NET Coreから成り立つ
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build-env
WORKDIR /App

# 全てのファイルをコンテナにコピーする
COPY . ./

# csprojを見て依存関係を解決する
RUN dotnet restore

# ビルドしてpublishする
RUN dotnet publish -c Release -o out


# DockerTestの実行
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /App
COPY --from=build-env /App/out .
ENTRYPOINT ["dotnet", "CloudRunSample.dll"]

ただしCloud Runではソースからのデプロイする場合、ソースコードからコンテナ イメージが自動的にビルドされて、デプロイされるようです。ですので今回は特に用意しません。

Cloud Runにデプロイする

$ gcloud run deploy
Deploying from source. To deploy a container use [--image]. See https://cloud.google.com/run/docs/deploying-source-code for more details.
Source code location (C:\Users\----\Desktop\CloudRunSample):  .
Next time, use `gcloud run deploy --source .` to deploy the current directory.

Service name (cloudrunsample):  cloudrunsample
Please specify a region:
 [1] africa-south1
 [2] asia-east1
 [3] asia-east2
 [4] asia-northeast1
 [5] asia-northeast2
 [6] asia-northeast3
 [7] asia-south1
 [8] asia-south2
 [9] asia-southeast1
 [10] asia-southeast2
 [11] australia-southeast1
 [12] australia-southeast2
 [13] europe-central2
 [14] europe-north1
 [15] europe-southwest1
 [16] europe-west1
 [17] europe-west10
 [18] europe-west12
 [19] europe-west2
 [20] europe-west3
 [21] europe-west4
 [22] europe-west6
 [23] europe-west8
 [24] europe-west9
 [25] me-central1
 [26] me-central2
 [27] me-west1
 [28] northamerica-northeast1
 [29] northamerica-northeast2
 [30] southamerica-east1
 [31] southamerica-west1
 [32] us-central1
 [33] us-east1
 [34] us-east4
 [35] us-east5
 [36] us-south1
 [37] us-west1
 [38] us-west2
 [39] us-west3
 [40] us-west4
 [41] cancel
Please enter numeric choice or text value (must exactly match list item):  4

To make this the default region, run `gcloud config set run/region asia-northeast1`.

Deploying from source requires an Artifact Registry Docker repository to store built containers. A repository named
[cloud-run-source-deploy] in region [asia-northeast1] will be created.

Do you want to continue (Y/n)?  y

This command is equivalent to running `gcloud builds submit --pack image=[IMAGE] .` and `gcloud run deploy cloudrunsample --image [IMAGE]`

Allow unauthenticated invocations to [cloudrunsample] (y/N)?  y

Building using Buildpacks and deploying container to Cloud Run service [cloudrunsample] in project [rock-data-417805] region [asia-northeast1]
✓ Building and deploying new service... Done.
  ✓ Creating Container Repository...
  ✓ Uploading sources...
  ✓ Building Container... Logs are available at [https://console.cloud.google.com/cloud-build/builds/--------].
  ✓ Creating Revision...
  ✓ Routing traffic...
  ✓ Setting IAM Policy...
Done.
Service [cloudrunsample] revision [cloudrunsample-00001-tqz] has been deployed and is serving 100 percent of traffic.
Service URL: https://--------.app

最後に記載されているService URLにアクセスすると、Hello, Worldが表示されていることが確認できればOKです。

Artifact Registry

gcloud run deployを実行した際にDeploying from source requires an Artifact Registry Docker repository to store built containers.という表示があったかと思いますが、Artifact Registryに自動でコンテナイメージが作成されて格納されています。

Artifact Registryにイメージが自動で生成されている