.NET 7 was released a few days ago with new features and performance improvements and it’s already supported on Cloud Run on Google Cloud!
In this short blog post, I show you how to deploy a .NET 7 web app to Cloud Run.
Create a .NET 7 web app
First, make sure you’re on .NET 7:
dotnet --version
7.0.100
Create a simple web app:
dotnet new web -o helloworld-dotnet7
This creates the helloworld-dotnet7
folder with a project file. I love
how simple the default Program.cs
file is nowadays:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
For Cloud Run, you need to check for PORT
and listen on 0.0.0.0
. Change
Program.cs
to the following:
var builder = WebApplication.CreateBuilder(args);
// Add the following for Cloud Run
var port = Environment.GetEnvironmentVariable("PORT") ?? "8080";
var url = $"http://0.0.0.0:{port}";
builder.WebHost.UseUrls(url);
var app = builder.Build();
app.MapGet("/", () => "Hello World from .NET 7.0!");
app.Run();
Test locally
Let’s run the app locally for a quick test.
Start the app:
dotnet run
Building...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://0.0.0.0:8080
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: /Users/atamel/dev/local/helloworld-dotnet7
Use curl to send a request:
curl http://localhost:8080
Hello World from .NET 7.0!
Deploy to Cloud Run
Deploy to Cloud Run:
gcloud run deploy helloworld-dotnet7 \
--allow-unauthenticated \
--region us-central1 \
--source .
Notice we’re using --source
flag. Behind the scenes, this command uses Google
Cloud buildpacks and Cloud
Build to automatically build container images from your source code without a
Dockerfile
or having to install Docker on your machine.
In a few minutes, the app is deployed to Cloud Run.
Test against Cloud Run
To test against the deployed Cloud Run, get the service url and use curl:
SERVICE_URL=$(gcloud run services describe helloworld-dotnet7 --region us-central1 --format 'value(status.url)')
curl $SERVICE_URL
Hello World from .NET 7.0!
Voila! .NET 7.0 running on Cloud Run.
For questions or feedback, feel free to reach out to me on Twitter @meteatamel.