Kubernetes has become the de facto standard for deploying and managing containerized applications at scale. In this post, we will see how to build a scalable ASP .NET Core app and deploy it on a Kubernetes cluster.
Benefits of Kubernetes for ASP .NET Core
Here are some key benefits Kubernetes provides for ASP .NET Core workloads:
Automated scaling - Kubernetes can automatically scale ASP .NET Core deployments up and down based on demand. This allows for handling large traffic spikes gracefully.
Load balancing - The Kubernetes service abstraction provides load balancing across ASP .NET Core pod replicas. Requests are evenly distributed for maximum resource utilization.
High availability - Kubernetes ensures high availability by distributing ASP .NET Core instances across nodes and automatically rescheduling failed containers.
Simplified deployment - Kubernetes enables deploying new ASP .NET Core versions through rolling updates with zero downtime. Infrastructure changes are minimal.
Observability - Kubernetes provides visibility into ASP .NET Core app metrics, logs, and tracing for monitoring and troubleshooting.
Cross-platform - Kubernetes is consistent across on-premise and cloud environments like AWS, Azure, and GCP. ASP .NET Core apps can be deployed anywhere.
Building a Sample ASP .NET Core App
We will build a simple ASP .NET Core web API for this demo that performs CRUD operations against a PostgreSQL database. It uses .NET 6 and Entity Framework Core.
The API has two endpoints:
GET /books
- Get all booksPOST /books
- Create a new book
Here is a code snippet showing the BooksController
:
// Omitted - Namespace declarations
[Route("api/[controller]")]
public class BooksController : ControllerBase
{
private readonly BookContext _context;
public BooksController(BookContext context)
{
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetBooks()
{
return Ok(await _context.Books.ToListAsync());
}
[HttpPost]
public async Task<IActionResult> AddBook(Book book)
{
_context.Books.Add(book);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetBooks), new { id =
book.Id
}, book);
}
}
The BookContext uses EF Core to connect with a PostgreSQL database to store book records.
Dockerizing the ASP .NET Core API
The first step is to Dockerize the ASP .NET Core API to deploy instances consistently across environments.
Here is a sample Dockerfile:
FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY . .
RUN dotnet restore "BooksAPI.csproj"
RUN dotnet build "BooksAPI.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "BooksAPI.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "BooksAPI.dll"]
This multi-stage Dockerfile builds the ASP .NET Core app as a Linux container image.
Configuring the Kubernetes Cluster
The next step is setting up a Kubernetes cluster on AWS EKS or Azure AKS and installing kubectl
CLI tool.
Some key resources need to be created:
Kubernetes Deployment - For deploying the ASP .NET Core pods
Service - For exposing the Deployment
Ingress - For routing external traffic to the Service
ConfigMap - For application config
Secret - For storing sensitive data like DB credentials
Here is an example deployment manifest:
apiVersion: apps/v1
kind: Deployment
metadata:
name: books-api
spec:
replicas: 3
selector:
matchLabels:
app: books-api
template:
metadata:
labels:
app: books-api
spec:
containers:
- name: books-api
image: booksapi:v1
ports:
- containerPort: 80
env:
- name: ConnectionStrings__BookDb
valueFrom:
secretKeyRef:
name: bookdb-secret
key: connection_string
This deploys 3 ASP .NET Core API container replicas and injects the database connection string from a Kubernetes secret.
Scaling the Application
One of the key advantages of Kubernetes is the ability to scale applications seamlessly.
Scaling the number of ASP .NET Core API replicas is as simple as changing the replicas
field and reapplying the deployment. Kubernetes will handle starting new pods to match the desired count.
For autoscaling based on demand, Kubernetes Horizontal Pod Autoscaler can be used. It automatically scales the number of pods between minimum and maximum limits based on CPU or memory utilization.
Handling Traffic with Ingress
A Kubernetes Ingress is used to route external traffic to the ASP .NET Core API. The Ingress works as a reverse proxy and load balancer.
For example:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: books-ingress
spec:
rules:
- http:
paths:
- path: /api/books
pathType: Prefix
backend:
service:
name: books-api-service
port:
number: 80
This will route external requests /api/books to the internal Service, exposing the ASP .NET Core API pods. Multiple APIs can be hosted on the same domain by using path-based routing.
Final Words
Deploying scalable and resilient ASP .NET Core applications is critical for enterprises seeking robust web solutions. Companies can build and run ASP .NET development services and Kubernetes at scale by leveraging ASP .NET Core workloads.
In this post, we deployed a sample ASP .NET Core API to a Kubernetes cluster. The benefits of Kubernetes for ASP .NET Core are numerous - automated scaling, load balancing, high availability, simplified deployment, and cross-platform portability.
For production workloads, aspects like monitoring, logs aggregation, security, and data persistence must also be considered. However, with expert ASP .NET development teams, these can be implemented following industry best practices. Kubernetes provides a modern way to deploy enterprise-grade ASP .NET Core applications and seamlessly handle scale. By partnering with specialized ASP.NET development services firms, robust and future-ready ASP .NET Core solutions can be built on Kubernetes.