.NET Tutorial - Your First Microservice

2021-03-08

Intro

Purpose

Become familiar with the building blocks for creating microservices with .NET.

Prerequisites

None.

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 (Software Development Kit).



Check everything installed correctly

Once you've installed, open a new command prompt and run the following command:

Command prompt

dotnet

If the installation succeeded, you should see an output similar to the following:

Command prompt

Usage: dotnet [options]
Usage: dotnet [path-to-application]
Options:
-h|--help         Display help.
--info            Display .NET information.
--list-sdks       Display the installed SDKs.
--list-runtimes   Display the installed runtimes.

path-to-application:
The path to an application .dll file to execute.

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 you can'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:

Command prompt

dotnet new webapi -o myMicroservice --no-https

Then, navigate to the new directory created by the previous command:

Command prompt

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 named myMicroservice 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 myNewMicroService directory, to give you a simple service that is ready to run.

  • myMicroservice.csproj defines what libraries the project references etc.

  • Startup.cs contains all the settings and configuration that are loaded when the app starts.

  • Controllers/WeatherForecastController.cs has code for a simple API that returns the weather forecast for the next five days.

WeatherForecastController.cs (shortened for clarity)

[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }}



Run your service

In your command prompt, run the following command:

Command prompt

dotnet run

Wait for the command to display that it's listening on http://localhost:5000, and then open a new browser window and navigate to

http://localhost:5000/WeatherForecast


screenshot-microservice-tutorial-run.png


Congratulations, you've got a simple service running!

PressCTRL+Con your command prompt to end the dotnet run command that is running the service locally.


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 18.09 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.


Check that Docker is ready to use

Once you've installed, open a new command prompt and run the following command:

Command prompt

docker --version

If the command runs, displaying some version information, then Docker is successfully installed.


Add Docker metadata

To run with 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.

Command prompt

cd myMicroservice

Add a DockerFile

Create a file called Dockerfile with the following content in a text editor:

Dockerfile

FROM mcr.microsoft.com/dotnet/sdk:5.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:5.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 the following content in a text editor:

.dockerignore

Dockerfile
[b|B]in
[O|o]bj


Create Docker image

Run the following command:

Command prompt

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 as mymicroservice.

  • The final parameter tells it which directory to use to find the Dockerfile (. specifies the current directory).

You can run the following command to see a list of all images available on your machine, including the one you just created.

Command prompt

docker images


Run Docker image

You can run your app in a container using the following command :

Command prompt

docker run -it --rm -p 3000:80 --name mymicroservicecontainer mymicroservice

Optionally, you can view your container running in a separate command prompt using the following command:

Command prompt

docker ps

You can browse to the following URL to access your application running in a container: http://localhost:3000/WeatherForecast


screenshot-microservice-tutorial-run-docker.png


PressCTRL+Con your command prompt 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.




联系信息

QQ:1827566828
Email: 1827566828@qq.com
Web: https://www.yynet.wang

留言