Building Microservices with .NET 9 and Docker: A Step-by-Step Guide

Meta Description: Learn how to build scalable microservices using .NET 9 and Docker. Follow this step-by-step guide for best practices, deployment tips, and optimization techniques....

By · · Updated · 7 min read · intermediate

Meta Description: Learn how to build scalable microservices using .NET 9 and Docker. Follow this step-by-step guide for best practices, deployment tips, and optimization techniques.


Introduction

Microservices architecture has revolutionized how modern applications are built, offering scalability, flexibility, and resilience. With the release of .NET 9, developers now have access to powerful tools and features to create high-performance microservices. When combined with Docker, deploying and managing these services becomes seamless and efficient.

In this guide, we’ll walk you through the process of building microservices using .NET 9 and Docker. Whether you're a beginner or an experienced developer, you'll find actionable steps, best practices, and tips to optimize your microservices for production. Let’s dive in!


Why Choose .NET 9 and Docker for Microservices?

Before we jump into the implementation, let’s explore why .NET 9 and Docker are an excellent choice for building microservices:

  • .NET 9 Performance: .NET 9 introduces significant performance improvements, reduced memory usage, and enhanced support for cloud-native applications.
  • Cross-Platform Compatibility: Docker allows you to containerize your microservices, ensuring they run consistently across different environments.
  • Scalability: Microservices can be independently scaled based on demand, and Docker simplifies the orchestration of these services.
  • Isolation: Each microservice runs in its own container, reducing conflicts and improving security.
  • CI/CD Integration: Docker integrates seamlessly with CI/CD pipelines, enabling automated testing and deployment.

Setting Up Your Development Environment

To get started, ensure you have the following tools installed:

  1. .NET 9 SDK: Download and install the latest .NET 9 SDK from the official .NET website.
  2. Docker Desktop: Install Docker Desktop for your operating system from Docker’s official site.
  3. IDE or Code Editor: Use Visual Studio, Visual Studio Code, or any other preferred code editor.
  4. Postman (Optional): For testing APIs, you can use Postman or any API testing tool.

Once installed, verify your setup by running the following commands in your terminal:

dotnet --version
docker --version

Creating Your First Microservice with .NET 9

Let’s create a simple microservice using .NET 9. We’ll build a basic Product API that allows you to manage product information.

Step 1: Create a New .NET 9 Project

Open your terminal and run the following command to create a new ASP.NET Core Web API project:

dotnet new webapi -n ProductService
cd ProductService

Step 2: Define the Product Model and Controller

  1. Create a Product Model: Add a new folder named Models and create a file called Product.cs:

    namespace ProductService.Models
    {
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public decimal Price { get; set; }
        }
    }
    
  2. Create a Controller: In the Controllers folder, create a file named ProductsController.cs:

    using Microsoft.AspNetCore.Mvc;
    using ProductService.Models;
    
    namespace ProductService.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ProductsController : ControllerBase
        {
            private static List<Product> _products = new List<Product>
            {
                new Product { Id = 1, Name = "Laptop", Price = 999.99m },
                new Product { Id = 2, Name = "Smartphone", Price = 699.99m }
            };
    
            [HttpGet]
            public IActionResult Get()
            {
                return Ok(_products);
            }
    
            [HttpGet("{id}")]
            public IActionResult Get(int id)
            {
                var product = _products.FirstOrDefault(p => p.Id == id);
                if (product == null)
                {
                    return NotFound();
                }
                return Ok(product);
            }
    
            [HttpPost]
            public IActionResult Post([FromBody] Product product)
            {
                _products.Add(product);
                return CreatedAtAction(nameof(Get), new { id = product.Id }, product);
            }
        }
    }
    }
    

Step 3: Run and Test the Microservice

Run the microservice using the following command:

dotnet run

Open your browser or Postman and navigate to https://localhost:5001/api/products to see the list of products.


Containerizing the Microservice with Docker

Now that your microservice is running locally, let’s containerize it using Docker.

Step 1: Create a Dockerfile

In the root directory of your ProductService project, create a file named Dockerfile (no extension) and add the following content:

# Use the official .NET 9 SDK image to build the app
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish -c Release -o /app

# Use the ASP.NET runtime image to run the app
FROM mcr.microsoft.com/dotnet/aspnet:9.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "ProductService.dll"]

Step 2: Build the Docker Image

Run the following command to build the Docker image:

docker build -t product-service .

Step 3: Run the Docker Container

Start the container using the following command:

docker run -p 8080:80 product-service

Now, your microservice is running inside a Docker container. You can access it at http://localhost:8080/api/products.


Deploying Microservices to a Container Orchestration Platform

While running a single container is useful for development, production environments require orchestration tools like Kubernetes or Docker Swarm to manage multiple containers. Here’s a brief overview of deploying your microservices:

Option 1: Docker Compose for Local Development

For local development with multiple microservices, use Docker Compose. Create a docker-compose.yml file:

version: '3.8'

services:
  product-service:
    image: product-service
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "8080:80"

Run the services using:

docker-compose up

Option 2: Kubernetes for Production

For production, consider using Kubernetes to manage your microservices. Here’s a simple example of a Kubernetes deployment file (deployment.yaml):

apiVersion: apps/v1
kind: Deployment
metadata:
  name: product-service
spec:
  replicas: 2
  selector:
    matchLabels:
      app: product-service
  template:
    metadata:
      labels:
        app: product-service
    spec:
      containers:
      - name: product-service
        image: product-service
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: product-service
spec:
  type: LoadBalancer
  ports:
  - port: 80
  selector:
    app: product-service

Apply the deployment using:

kubectl apply -f deployment.yaml

Best Practices for Building Microservices with .NET 9 and Docker

To ensure your microservices are scalable, maintainable, and secure, follow these best practices:

1. Keep Microservices Small and Focused

  • Each microservice should have a single responsibility (e.g., Product Service, Order Service).
  • Avoid creating monolithic services within your microservices architecture.

2. Use API Gateways

  • Implement an API gateway (e.g., Ocelot, Kong) to manage routing, load balancing, and authentication.

3. Implement Health Checks

  • Add health check endpoints to monitor the status of your microservices.
  • Example in .NET 9:
    builder.Services.AddHealthChecks();
    app.MapHealthChecks("/health");
    

4. Optimize Docker Images

  • Use multi-stage builds to reduce image size.
  • Avoid including unnecessary files in your Docker context.

5. Secure Your Microservices

  • Use HTTPS for all communications.
  • Implement authentication and authorization (e.g., JWT, OAuth).

6. Monitor and Log

  • Use tools like Prometheus, Grafana, and ELK Stack for monitoring and logging.

7. Automate Testing and Deployment

  • Implement CI/CD pipelines (e.g., GitHub Actions, Azure DevOps) to automate testing and deployment.

Conclusion

Building microservices with .NET 9 and Docker provides a robust, scalable, and efficient way to develop modern applications. In this guide, we covered:

  • The benefits of using .NET 9 and Docker for microservices.
  • Setting up your development environment.
  • Creating a basic microservice with .NET 9.
  • Containerizing the microservice using Docker.
  • Deploying microservices to Docker Compose and Kubernetes.
  • Best practices for optimizing and securing your microservices.

By following these steps and best practices, you’ll be well on your way to building high-performance, scalable microservices that meet the demands of modern applications.


Call to Action

Ready to take your microservices to the next level? Start by experimenting with the steps outlined in this guide. Once you’ve mastered the basics, explore advanced topics like service discovery, event-driven architecture, and serverless integration.

If you found this guide helpful, share it with your network or leave a comment below with your thoughts and questions. Happy coding! 🚀