Creating an API Gateway using Ocelot.NET and Consul in ASP.NET Core (.NET 5) with Docker

Prerequisites

  • Docker Desktop (for running our services and deploying Consul)
    https://www.docker.com/products/docker-desktop
  • IDE of choice, however, I highly recommend Visual Studio because of the simplified docker integration.
  • .NET 5 SDK Installed
  • Basic knowledge about ASP.NET Core and Docker.

Tutorial Content

  1. Deploying Consul using Docker Desktop.
  2. Creating a sample API (microservice 1) and registering it with Consul
  3. Creating the API Gateway using Ocelot.NET and integrating Consul

1 Deploying Consul using Docker Desktop

Open your Terminal/Command Prompt

docker run -d — name=dev-consul -p 8500:8500 -p 8600:8600 — restart unless-stopped consul
docker container list
docker container list — results

2 Creating a sample API and registering it with Consul

Next up is creating a simple API. I’ll be using the default Web API template from Asp.NET Core

Visual Studio Project Settings
  • ServiceName = Name of the service.
  • ServicePort = Http/Https Port of the service.
services.AddHealthChecks();
services.AddConsulConfig(Configuration);
app.UseConsul(Configuration);
app.UseEndpoints(endpoints =>{  endpoints.MapHealthChecks(“/health”);
endpoints.MapControllers();
});
docker build -t sampleapi .docker run sampleapi
Consul showing our SampleAPI

3 Creating the API Gateway using Ocelot.NET and integrating Consul

Create a new ASP.NET Core project, this time I’ll be using the ASP.NET Core Empty template.

docker build -t apigateway.docker run apigateway -p <HOSTPORT>:80
launchSettings.json Docker section
WeatherForecast results from our API Gateway

Short Coding Tutorials for .NET & NodeJS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store