Skip to content

Xjectro/dotnet-microservice

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

.NET Microservice Boilerplate with Ocelot API Gateway

A production-ready .NET 10 microservice boilerplate featuring Ocelot API Gateway, JWT authentication, Prometheus + Grafana monitoring, Docker Compose (multi-environment), and Kubernetes deployment.

Docker-only: This project has no appsettings.json files. All configuration is provided through environment variables managed by Docker Compose. Running the services requires Docker.


Architecture

                      ┌────────────┐
                      │   Client   │
                      └─────┬──────┘
                            │
                            ▼
               ┌────────────────────────┐
               │  API Gateway (Ocelot)  │
               │  http://localhost:5050 │
               └──┬─────────┬────────┬──┘
                  │         │        │
        ┌─────────┘         │        └──────────┐
        ▼                   ▼                    ▼
  ┌───────────┐     ┌────────────┐      ┌────────────┐
  │ Identity  │     │  Product   │      │   Order    │
  │  Service  │     │  Service   │      │  Service   │
  │   :5001   │     │   :5002    │      │   :5003    │
  └───────────┘     └────────────┘      └────────────┘

        ┌────────────────────────────────────────┐
        │         Monitoring Stack               │
        │  Prometheus :9090  ·  Grafana :3000    │
        └────────────────────────────────────────┘

Project Structure

.
├── Makefile                              # All build, run, deploy commands
├── Microservice.sln                      # .NET solution file
├── src/
│   ├── ApiGateway/                       # Ocelot API Gateway
│   │   ├── Program.cs
│   │   ├── ocelot.json                   # Production routing (container names)
│   │   └── ocelot.Development.json       # Development routing (localhost)
│   ├── Services/
│   │   ├── Identity/Identity.API/        # JWT auth service (register, login)
│   │   ├── Product/Product.API/          # Product CRUD service
│   │   └── Order/Order.API/             # Order management service
│   └── Shared/Shared.Common/            # Shared library
│       ├── Models/                       # ApiResponse<T>, JwtSettings
│       ├── Middleware/                   # Global exception handling
│       └── Extensions/                  # JWT authentication extension
├── docker/
│   ├── docker-compose.base.yml          # Shared service definitions
│   ├── docker-compose.local.yml         # Local/dev overlay
│   ├── docker-compose.test.yml          # Test overlay
│   ├── docker-compose.production.yml    # Production overlay
│   ├── env/
│   │   ├── .env.local                   # Local environment variables
│   │   ├── .env.test                    # Test environment variables
│   │   └── .env.production              # Production environment variables
│   └── images/
│       ├── api-gateway/Dockerfile
│       ├── identity-api/Dockerfile
│       ├── product-api/Dockerfile
│       └── order-api/Dockerfile
├── k8s/                                 # Kubernetes manifests (Kustomize)
│   ├── kustomization.yaml
│   ├── namespace.yaml
│   ├── jwt-secret.yaml
│   ├── ocelot-configmap.yaml
│   ├── ingress.yaml
│   ├── hpa.yaml
│   ├── network-policy.yaml
│   ├── gateway/
│   ├── services/
│   └── monitoring/
└── monitoring/
    ├── prometheus/prometheus.yml         # Scrape configuration
    └── grafana/
        ├── dashboards/                   # Pre-built dashboard JSON
        └── provisioning/                 # Datasource & dashboard providers

Prerequisites


Quick Start

# Start all services in local/dev mode
make up

# Check service health
make health

# View logs
make logs

# Stop everything
make down

Environments

The project supports three environments using Docker Compose overlays:

Environment Command Env File Restart Policy Resource Limits
Local make local-up .env.local none none
Test make test-up .env.test unless-stopped none
Production make prod-up .env.production always 256 MB / 0.50 CPU

Each environment uses a base + overlay compose pattern:

# Base (shared definitions) + Overlay (env-specific) + Env file
docker compose \
  -f docker/docker-compose.base.yml \
  -f docker/docker-compose.local.yml \
  --env-file docker/env/.env.local \
  up -d --build

The Makefile wraps all of this — you only need make local-up, make test-up, or make prod-up.


Configuration

All configuration is injected via environment variables. Edit the corresponding .env file under docker/env/.

Key Variables

Variable Description Example
ASPNETCORE_ENVIRONMENT Runtime environment Development, Testing, Production
JWT_SECRET JWT signing key (≥ 32 chars) YourSuperSecretKey...
JWT_ISSUER JWT issuer claim MicroserviceApp
JWT_AUDIENCE JWT audience claim MicroserviceApp
JWT_EXPIRATION_MINUTES Token lifetime 60
LOGGING_LOGLEVEL_DEFAULT Default log level Debug, Information, Warning
API_GATEWAY_PORT Host port for gateway 5050

Port Mapping

Service Container Port Default Host Port
API Gateway 5050 5050
Identity API 5001 5001
Product API 5002 5002
Order API 5003 5003
Prometheus 9090 9090
Grafana 3000 3000

⚠️ Production: Replace all CHANGE_ME values in docker/env/.env.production with strong secrets before deploying.


API Endpoints

All requests are routed through the API Gateway at http://localhost:5050.

Identity Service

Method Endpoint Description Auth
POST /api/auth/register Register a new user
POST /api/auth/login Login & get JWT token

Product Service

Method Endpoint Description Auth
GET /api/products List all products
GET /api/products/{id} Get product by ID
POST /api/products Create a product
PUT /api/products/{id} Update a product
DELETE /api/products/{id} Delete a product

Order Service

Method Endpoint Description Auth
GET /api/orders List all orders
GET /api/orders/{id} Get order by ID
POST /api/orders Create an order
PUT /api/orders/{id}/status Update order status
DELETE /api/orders/{id} Cancel an order

Health & Metrics

Endpoint Description
/health Health check (every service)
/metrics Prometheus metrics (every service)

Usage Example

1. Register

curl -X POST http://localhost:5050/api/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "email": "test@example.com",
    "password": "Password123!",
    "fullName": "Test User"
  }'

2. Login

curl -X POST http://localhost:5050/api/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "username": "testuser",
    "password": "Password123!"
  }'

3. Create a product (with token)

curl -X POST http://localhost:5050/api/products \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <TOKEN>" \
  -d '{
    "name": "Wireless Mouse",
    "description": "Ergonomic wireless mouse",
    "price": 29.99,
    "stock": 100,
    "category": "Electronics"
  }'

Monitoring

Prometheus and Grafana start automatically with every environment.

Tool URL Credentials
Prometheus http://localhost:9090
Grafana http://localhost:3000 admin / admin (local)

What's Monitored

  • HTTP request duration & rate
  • Request count by status code
  • Requests in progress
  • .NET runtime metrics (GC, thread pool, etc.)
  • Health check status

A pre-built Grafana dashboard is auto-provisioned with 9 panels covering all key .NET metrics.

Start Monitoring Only

make monitoring-up
make monitoring-down

Kubernetes Deployment

Validate Manifests

make k8s-validate

Deploy

# Deploy to current kubectl context
make k8s-deploy

# Deploy with a container registry
REGISTRY=ghcr.io/your-org TAG=v1.0.0 make k8s-deploy

Manage

make k8s-status    # Show pods, services, ingress, HPA
make k8s-logs      # Follow all pod logs
make k8s-delete    # Remove all resources

K8s Resources Included

  • Namespace: microservice
  • Deployments: All 4 services + Prometheus + Grafana
  • Services: ClusterIP for each deployment
  • Ingress: NGINX ingress with path-based routing
  • HPA: Horizontal Pod Autoscaler (CPU-based)
  • NetworkPolicy: Inter-service communication rules
  • ConfigMap: Ocelot routing + Prometheus config
  • Secret: JWT signing key

Makefile Commands

Run make help to see all available commands.

.NET

Command Description
make restore Restore NuGet packages
make build Build the solution
make run Start services via Docker (alias for local-up)
make test Run tests
make clean Clean build artifacts

Docker

Command Description
make docker-build Build all Docker images
make docker-clean Remove containers, volumes, and images

Local Environment

Command Description
make local-up Start all services (dev mode)
make local-down Stop and remove containers
make local-restart Rebuild and restart
make local-logs Follow container logs
make local-ps List running containers

Test Environment

Command Description
make test-up Start all services (test mode)
make test-down Stop and remove containers
make test-restart Rebuild and restart
make test-logs Follow container logs

Production Environment

Command Description
make prod-up Start all services (prod mode)
make prod-down Stop and remove containers
make prod-restart Rebuild and restart
make prod-logs Follow container logs

Single Service

Command Description
make up-<service> Start one service (e.g. make up-identity-api)
make down-<service> Stop one service
make logs-<service> Follow one service's logs
make restart-<service> Restart one service

Monitoring & Health

Command Description
make health Check health of all services
make monitoring-up Start Prometheus + Grafana only
make monitoring-down Stop monitoring stack

Shortcuts

Shortcut Equivalent
make up make local-up
make down make local-down
make local make local-up
make prod make prod-up
make ps make local-ps
make logs make local-logs
make restart make local-restart

Features

  • Ocelot API Gateway — Centralized routing, response caching
  • JWT Authentication — Shared token validation across services
  • Global Exception Handling — Common error middleware
  • Standard API Response — Consistent ApiResponse<T> wrapper
  • Docker Compose (Multi-Env) — Base + overlay pattern for local / test / production
  • Prometheus Metrics — HTTP request metrics, .NET runtime metrics
  • Grafana Dashboards — Pre-provisioned dashboard with 9 panels
  • Kubernetes Ready — Kustomize manifests with HPA, Ingress, NetworkPolicy
  • Health Checks/health endpoint on every service
  • Makefile Workflow — Single entry point for all operations

License

MIT

About

A production-ready .NET 10 microservice boilerplate featuring Ocelot API Gateway, JWT authentication, Prometheus + Grafana monitoring, Docker Compose (multi-environment), and Kubernetes deployment.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors