.NET Tutorial - Your First Microservice
Intro
Purpose
Become familiar with the building blocks for creating microservices with .NET.
Prerequisites
None.
macOS 12.0 or later versions.
Time to Complete
15 minutes
Scenario
Create a simple service that returns a list of values, then run the service in a Docker container.
Install .NET SDK
To start building .NET apps, download and install the .NET SDK.
Download .NET 8 SDK (64-bit)
32-bit download
|
Arm64 download
You need to install additional dependencies on older versions of Windows. See Windows 7 / 8.1 / Server 2012 for more information.
Download .NET 8 SDK x64 (Intel)
Download .NET 8 SDK Arm64 (Apple Silicon)
If you're on a Mac with an Apple M1 or M2 chip, you need to install the Arm64 version of the SDK.
Check everything installed correctly
Once you've installed, open a new command prompt and run the following command:
Once you've installed, open a new terminal and run the following command:
dotnet --version
If the installation succeeded, you should see version 8.0.100 or higher outputted:
8.0.100
If everything looks good, select the Continue button below to go to the next step.
Got an error?
If you receive a 'dotnet' is not recognized as an internal or external command error, make sure you opened a new command prompt. If quickly restarting your machine doesn't resolve the issue, use the I ran into an issue button to get help fixing the problem.
Create your service
In your command prompt, run the following command to create your app:
In your terminal, run the following command to create your app:
dotnet new webapi -o MyMicroservice --no-https
Then, navigate to the new directory created by the previous command:
cd MyMicroservice
What do these commands mean?
The dotnet
command creates a new application of type webapi
(that's a REST API endpoint).
- The
-o
parameter creates a directory namedMyMicroservice
where your app is stored. - The
--no-https
flag creates an app that will run without an HTTPS certificate, to keep things simple for deployment.
The cd MyMicroservice
command puts you into the newly created app directory.
The generated code
Several files were created in the MyMicroservice
directory, to give you a simple service that is ready to run, including the following files:
Program.cs
is the entry point file and contains all the settings and configuration that are loaded when the app starts and has code for a simple API that returns the weather forecast for the next five days. It also starts the application.MyMycroservice.http
is used for testing ASP.NET Core projects.MyMicroservice.csproj
defines the version of .NET the app is targeting, what libraries the project references, etc.- The
launchSettings.json
file inside theProperties
directory defines different profile settings for the local development environment. A port number ranging between 5000-5300 is automatically assigned at project creation and saved on this file.
The following code shows the contents of the Program.cs
file:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
Select the Continue button below to go to the next step.
Got an error?
If you receive a message similar to Template "ASP.NET Core Web API" could not be created. Failed to create template. Details: Access to the path 'C:\Windows\System32\MyMicroservice' is denied, change your current directory to one where you have permissions to create a new folder and try to run the command again.
If Windows can't find the SDK when you try to create the project and you are sure you have installed the SDK, your machine might have an issue with the PATH environment variable. See this Stack Overflow post for instructions on how to diagnose and fix this issue.
If you can't resolve the issue you're having, select the I ran into an issue button below to get help fixing the problem.
Run your service
In your command prompt, run the following command:
In your terminal, run the following command:
dotnet run
You should see an output similar to the following:
Building...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5020
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: C:\Users\Ana\MyMicroservice
Wait for the app to display that it's listening on http://localhost:<port number>, and then open a browser and navigate to http://localhost:<port number>/weatherforecast.
In this example, it showed that it was listening on port 5020, so the following image shows the URL localhost:5020/weatherforecast
.
Congratulations, you've got a simple service running!
Press CTRL+C on your command prompt to end the dotnet run
command that is running the service locally.
Press CTRL+C on your terminal to end the dotnet run
command that is running the service locally.
Got an error?
If you receive a message similar to No webpage was found for the web address: http://localhost:5020, ensure you are viewing the Weather Forecast page of your application. The URL should look like http://localhost:5020/weatherforecast and not just http://localhost:5020.
Install Docker
Docker is a platform that enables you to combine an app plus its configuration and dependencies into a single, independently deployable unit called a container.
If you already have Docker installed, make sure it's version 23.0.0 or higher.
Download and install
You'll be asked to register for Docker Store before you can download the installer.
By default, Docker will use Linux Containers on Windows. Leave this configuration settings as-is when prompted in the installer.
After installing Docker, you may be asked to sign out to finalize installation.
Check that Docker is ready to use
Once you've installed, open a new command prompt and run the following command:
Once you've installed, open a new terminal and run the following command:
docker --version
If the command runs, displaying some version information, then Docker is successfully installed.
Add Docker metadata
To run with a Docker image, you need a Dockerfile
— a text file that contains instructions for how to build your app as a Docker image. A Docker image contains everything needed to run your app as a Docker container.
Return to app directory
Since you opened a new command prompt in the previous step, you'll need to return to the directory you created your service in.
Since you opened a new terminal in the previous step, you'll need to return to the directory you created your service in.
cd MyMicroservice
Add a DockerFile
Create a file called Dockerfile
with this command:
touch Dockerfile
fsutil file createnew Dockerfile 0
You can then open it in your favorite text editor.
You can then open it in your favorite text editor manually or with this command:
open Dockerfile
start Dockerfile
Replace the content of the Dockerfile
to the following in the text editor:
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY MyMicroservice.csproj .
RUN dotnet restore
COPY . .
RUN dotnet publish -c release -o /app
FROM mcr.microsoft.com/dotnet/aspnet:8.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "MyMicroservice.dll"]
Note: Make sure to name the file as Dockerfile
and not Dockerfile.txt
or some other name.
Optional: Add a .dockerignore file
A .dockerignore file reduces the set of files that are used as part of `docker build`. Fewer files will result in faster builds.
Create a file called .dockerignore
file (this is similar to a .gitignore
file if you're familiar with those) with this command:
touch .dockerignore
fsutil file createnew .dockerignore 0
You can then open it in your favorite text editor.
You can then open it in your favorite text editor manually or with this command:
open .dockerignore
start .dockerignore
Replace the content of the .dockerignore
to the following in the text editor:
Dockerfile
[b|B]in
[O|o]bj
Create Docker image
Run the following command:
docker build -t mymicroservice .
The docker build
command uses the Dockerfile
to build a Docker image.
- The
-t mymicroservice
parameter tells it to tag (or name) the image asmymicroservice
. - The final parameter tells it which directory to use to find the
Dockerfile
(.
specifies the current directory). - This command will download and build all dependencies to create a Docker image and may take some time.
You can run the following command to see a list of all images available on your machine, including the one you just created.
docker images
Run Docker image
You can run your app in a container using the following command:
docker run -it --rm -p 3000:8080 --name mymicroservicecontainer mymicroservice
You can browse to the following URL to access your application running in a container: http://localhost:3000/weatherforecast
Optionally, you can view your container running in a separate command prompt using the following command:
Optionally, you can view your container running in a separate terminal window using the following command:
docker ps
Press CTRL+C on your command prompt to end the docker run
command that is running the service in a container.
Press CTRL+C on your terminal to end the docker run
command that is running the service in a container.
Congratulations! You've successfully created a small, independent service that can be deployed and scaled using Docker containers.
These are the fundamental building blocks of microservices.
Got an error?
If you receive a message similar to ERROR: error during connect: this error may indicate that the docker daemon is not running, it may indicate that you need to launch the Docker application. Check that the Docker client is running by running docker run hello-world
. This should pull and run the image. For more help, see the Docker documentation for instructions on how to diagnose and fix this issue.
Next steps
Congratulations! You've created a simple service and then ran it in a Docker container.
Now, you can learn how to deploy your microservice to the cloud with our next tutorial.
Tutorial: Deploy microservice to Azure
You might also be interested in...