Microservices have become the standard for building scalable, resilient, and maintainable applications. With the release of .NET 8, Microsoft has introduced powerful features that simplify microservices architecture, including native container support, minimal APIs, performance optimizations, and cloud-native integrations.
This article will take a deep dive into designing, developing, deploying, and optimizing microservices using .NET 8 and Kubernetes (K8s). You will learn how to:
- Architect microservices effectively.
- Implement communication between microservices.
- Secure and scale microservices using Kubernetes.
- Deploy .NET 8 microservices on AWS using EKS (Elastic Kubernetes Service).
1. Understanding Microservices Architecture
Microservices break a monolithic application into small, independent services that:
✅ Are loosely coupled – Each service can be developed, deployed, and scaled independently.
✅ Have separate databases – Prevents shared data bottlenecks.
✅ Communicate via APIs (REST, gRPC, GraphQL, Message Queues).
✅ Enable scalability – Individual services scale based on demand.
Here’s an example microservices architecture for an e-commerce application:
- User Service (Identity, Authentication, JWT)
- Product Service (Catalog, Pricing)
- Order Service (Cart, Checkout, Payment)
- Inventory Service (Stock management)
- Notification Service (Emails, SMS)
These services communicate over HTTP (REST), gRPC, or event-driven messaging (Kafka, RabbitMQ).
2. Setting Up a .NET 8 Microservice
Step 1: Create a Minimal API in .NET 8
.NET 8 introduced Minimal APIs, making it easier to create lightweight microservices.
Create a new microservice for managing products:
dotnet new webapi -n ProductService
cd ProductService
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.AspNetCore.OpenApi
Define the Product
model:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Create the API endpoints in Program.cs
:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ProductDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
app.MapGet("/products", async (ProductDbContext db) =>
await db.Products.ToListAsync());
app.MapPost("/products", async (Product product, ProductDbContext db) =>
{
db.Products.Add(product);
await db.SaveChangesAsync();
return Results.Created($"/products/{product.Id}", product);
});
app.Run();
This is a minimal, production-ready microservice for managing products.
3. Deploying the Microservice as a Docker Container
Microservices run best in containers because they ensure consistency across environments.
Step 1: Create a Dockerfile
Inside the ProductService
folder, create a Dockerfile
:
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet restore
RUN dotnet publish -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "ProductService.dll"]
Step 2: Build and Run the Container
docker build -t productservice .
docker run -d -p 8080:80 --name productservice productservice
Now, your microservice runs inside a Docker container on port 8080.
4. Orchestrating Microservices with Kubernetes
Kubernetes (K8s) helps manage multiple microservices by providing auto-scaling, service discovery, and load balancing.
Step 1: Create a Kubernetes Deployment
Create a product-service.yaml
file:
apiVersion: apps/v1
kind: Deployment
metadata:
name: product-service
spec:
replicas: 3
selector:
matchLabels:
app: product-service
template:
metadata:
labels:
app: product-service
spec:
containers:
- name: product-service
image: your-docker-hub-username/productservice:latest
ports:
- containerPort: 80
This ensures 3 replicas of the Product Service run on Kubernetes.
Step 2: Create a Kubernetes Service
apiVersion: v1
kind: Service
metadata:
name: product-service
spec:
selector:
app: product-service
ports:
- protocol: TCP
port: 80
targetPort: 80
type: LoadBalancer
This exposes the service using a LoadBalancer.
Step 3: Deploy on Kubernetes
kubectl apply -f product-service.yaml
Now, your microservice is running on Kubernetes! 🎉
5. Communication Between Microservices
Microservices need to communicate efficiently. You can use:
A. REST API Calls (For simple synchronous communication)
var client = new HttpClient();
var response = await client.GetStringAsync("http://product-service/products");
B. gRPC (Faster than REST for internal communication)
service ProductService {
rpc GetProduct(ProductRequest) returns (ProductReply);
}
gRPC reduces latency compared to REST.
C. Event-Driven Messaging (Kafka/RabbitMQ for decoupled microservices)
When services should not depend on direct API calls, use event-driven messaging:
bus.Publish(new ProductCreatedEvent { ProductId = product.Id });
This improves scalability since services communicate asynchronously.
6. Securing Microservices in .NET 8
Microservices require strong security since they expose APIs over the network.
A. Authentication with JWT
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://secure-auth-provider.com";
options.Audience = "product-api";
});
Now, all requests must include a JWT token.
B. API Gateway for Security & Traffic Control
Instead of exposing microservices directly, use API Gateway (Ocelot):
{
"Routes": [
{
"DownstreamPathTemplate": "/products",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [{ "Host": "product-service", "Port": 80 }],
"UpstreamPathTemplate": "/api/products",
"UpstreamHttpMethod": [ "Get" ]
}
]
}
Ocelot provides authentication, rate limiting, and request validation.
7. Deploying Microservices to AWS Kubernetes (EKS)
AWS Elastic Kubernetes Service (EKS) manages Kubernetes clusters efficiently.
Step 1: Create an EKS Cluster
eksctl create cluster --name microservices-cluster --region us-east-1
Step 2: Deploy Microservices
kubectl apply -f product-service.yaml
Your .NET 8 microservices are now running in the cloud! 🚀
Conclusion
This guide covered designing, developing, and deploying microservices using .NET 8 and Kubernetes. Key takeaways:
✅ Use Minimal APIs for lightweight microservices.
✅ Deploy services in Docker containers.
✅ Orchestrate with Kubernetes (K8s).
✅ Communicate via REST, gRPC, or Kafka.
✅ Secure with JWT & API Gateway.
✅ Deploy to AWS EKS for scalability.
Want to go deeper? The next article will cover Serverless .NET 8 APIs with AWS Lambda and DynamoDB! 🎯