Building a Microservices Demo with Traefik on Kubernetes
Modern web applications require robust routing and load balancing to handle traffic efficiently. Traefik, a modern reverse proxy and load balancer, has become increasingly popular for its dynamic configuration and cloud-native design. In this comprehensive guide, we’ll build a complete microservices demo using Traefik as an ingress controller on Kubernetes, demonstrating how to route traffic to different services based on URL paths.
By the end of this tutorial, you’ll have a fully functional demo application with multiple microservices, all orchestrated through Traefik routing. This hands-on approach will give you practical experience with Kubernetes ingress controllers and microservices architecture.
What We’ll Build
Our demo application will include:
- Frontend Service: A web interface displaying the demo application’s homepage
- API Service: RESTful endpoints for book data management
- User Service: Authentication and user management endpoints
- Traefik: Acting as the ingress controller to route traffic
The architecture will demonstrate path-based routing where:
/
routes to the frontend service/api/*
routes to the API service/users/*
routes to the user service/dashboard/
provides access to Traefik’s management interface
Prerequisites
Before we begin, ensure you have the following installed:
- Docker: For containerization
- kind (Kubernetes in Docker): For local Kubernetes cluster
- kubectl: Kubernetes command-line tool
- Basic understanding of Kubernetes concepts: Pods, Services, Deployments
If you haven’t installed these tools, you can find installation guides on their respective official websites.
Project Structure
Our project follows a clean, organized structure:
1 | Traefik-demo/ |
This structure separates Traefik configuration from application services, making it easy to manage and scale.
Creating the KinD Cluster
First, let’s create a local Kubernetes cluster using KinD (Kubernetes in Docker). We’ll use a custom configuration that exposes the necessary ports for our services.
Create a kind-config.yaml
file with the following configuration:
1 | # Kind cluster configuration for Traefik |
This configuration creates a multi-node cluster with:
- One control-plane node with ingress-ready label
- Two worker nodes for workload distribution
- Port mappings for HTTP (80), HTTPS (443), and Traefik dashboard (8080)
Create the cluster:
1 | kind create cluster --name traefik-demo --config kind-config.yaml |
Installing Traefik CRDs
Traefik uses Custom Resource Definitions (CRDs) to extend Kubernetes with Traefik-specific resources like IngressRoute and Middleware. Install the required CRDs:
1 | kubectl apply -f https://raw.githubusercontent.com/traefik/traefik/v3.0/docs/content/reference/dynamic-configuration/kubernetes-crd-definition-v1.yml |
These CRDs enable us to use advanced Traefik features like path stripping and custom routing rules.
Setting Up Traefik
Namespace and RBAC Configuration
Create the Traefik namespace:
1 | apiVersion: v1 |
Set up the service account and permissions:
1 | apiVersion: v1 |
Traefik Deployment
Deploy Traefik with the following configuration:
1 | apiVersion: apps/v1 |
Key configuration points:
- API Dashboard: Enabled with insecure mode for demo purposes
- Entry Points: Web (80) and WebSecure (443)
- Providers: Both CRD and standard Ingress support
- Health Checks: Liveness and readiness probes
- Node Placement: Scheduled on the control-plane node
Creating the Demo Bookstore Application
Frontend Service
The frontend serves as the main landing page for our bookstore:
1 | apiVersion: apps/v1 |
The frontend includes an HTML page that provides:
- Welcome message and service information
- Links to test API endpoints
- Architecture overview
- Navigation to the Traefik dashboard
API Service
The API service handles book data and provides RESTful endpoints:
1 | apiVersion: apps/v1 |
The API service provides:
/books
- Returns a JSON list of available books/health
- Health check endpoint- Root endpoint with API information
User Service
The user service manages authentication and user profiles:
1 | apiVersion: apps/v1 |
Endpoints include:
/profile
- User profile information/login
- Authentication endpoint/health
- Health check
Configuring Traefik Routing
Middlewares
Traefik middlewares modify requests before forwarding them to services. We use stripPrefix
middleware to remove URL prefixes:
1 | apiVersion: traefik.io/v1alpha1 |
These middlewares ensure that:
- Requests to
/api/books
become/books
when forwarded to the API service - Requests to
/users/profile
become/profile
when forwarded to the user service
IngressRoute Configuration
The IngressRoute defines how Traefik routes traffic:
1 | apiVersion: traefik.io/v1alpha1 |
Important: The order of routes matters! More specific routes (/api
, /users
) must come before the catch-all route (/
).
Deployment and Testing
Deploy All Resources
Apply all the Traefik resources:
1 | kubectl apply -f base/traefik/ |
Deploy the bookstore application:
1 | kubectl apply -f base/bookstore/ |
Verify the Deployment
Check that all pods are running:
1 | kubectl get pods -A |
You should see:
- Traefik pod in
traefik-system
namespace - Frontend, API, and user service pods in
bookstore
namespace
Testing the Application
Frontend Service: Visit
http://localhost
- Should display the bookstore homepage
- Contains links to test other services
API Endpoints:
http://localhost/api/books
- Returns book data in JSONhttp://localhost/api/health
- API health status
User Endpoints:
http://localhost/users/profile
- User profile datahttp://localhost/users/login
- Login information
Traefik Dashboard:
http://localhost:9000/dashboard/
- Shows routing configuration
- Displays service health status
- Provides traffic metrics
Understanding the Architecture
Traffic Flow
- Client Request: Browser makes request to
http://localhost/api/books
- Traefik Reception: Traefik receives the request on port 80
- Route Matching: Traefik matches the request against IngressRoute rules
- Middleware Processing:
strip-api-prefix
removes/api
from the path - Service Forwarding: Modified request (
/books
) is sent to the API service - Response: API service responds with book data
- Client Response: Traefik forwards the response to the client
Service Discovery
Traefik automatically discovers services through:
- Kubernetes API: Watches for IngressRoute and Service changes
- Dynamic Configuration: Updates routing rules without restart
- Health Checking: Monitors service health through readiness probes
Load Balancing
Each service runs with 2 replicas, and Traefik automatically:
- Distributes traffic across healthy instances
- Removes unhealthy instances from rotation
- Provides session affinity if configured
Troubleshooting Common Issues
Pod Not Starting
Check pod logs:
1 | kubectl logs -n traefik-system deployment/traefik |
Routing Not Working
Verify IngressRoute configuration:
1
kubectl get ingressroute -n bookstore -o yaml
Check Traefik dashboard for route status
Ensure middleware names match between definitions and usage
Port Conflicts
If ports 80 or 8080 are already in use:
- Stop conflicting services
- Or modify the kind-config.yaml to use different ports
Service Discovery Issues
Verify that:
- Services have correct selectors
- Pods have matching labels
- Services are in the correct namespace
Advanced Configuration Options
HTTPS/TLS Configuration
To enable HTTPS:
1 | apiVersion: traefik.io/v1alpha1 |
Rate Limiting
Add rate limiting middleware:
1 | apiVersion: traefik.io/v1alpha1 |
Authentication
Configure basic auth:
1 | apiVersion: traefik.io/v1alpha1 |
Production Considerations
Security Hardening
- Disable Insecure API: Remove
--api.insecure=true
in production - Enable TLS: Configure proper certificates
- Network Policies: Restrict pod-to-pod communication
- RBAC: Use minimal required permissions
High Availability
- Multiple Replicas: Run multiple Traefik instances
- Anti-Affinity: Ensure replicas run on different nodes
- Health Checks: Configure appropriate probe settings
- Resource Limits: Set CPU and memory limits
Monitoring and Observability
- Metrics: Enable Prometheus metrics collection
- Logging: Configure structured logging
- Tracing: Integrate with Jaeger or Zipkin
- Alerting: Set up alerts for service health
Cleanup
To remove the demo environment:
1 | # Delete the Kubernetes cluster |
This removes all resources and frees up system resources.
Conclusion
In this comprehensive guide, we’ve built a complete microservices demo using Traefik on Kubernetes. We’ve covered:
- Setting up a local Kubernetes cluster with KinD
- Installing and configuring Traefik as an ingress controller
- Creating multiple microservices with different responsibilities
- Implementing path-based routing with middlewares
- Testing and troubleshooting the complete system
This demo provides a solid foundation for understanding how Traefik works in a microservices architecture. The concepts and configurations shown here can be adapted for production use with appropriate security and scalability considerations.
Traefik’s dynamic configuration capabilities make it an excellent choice for modern cloud-native applications where services are frequently updated and deployed. Its integration with Kubernetes through CRDs provides a powerful and flexible routing solution that scales with your application needs.
The hands-on experience gained from this tutorial will help you implement similar solutions in your own projects, whether you’re building new microservices architectures or migrating existing monolithic applications. You can find required files and configurations in the GitHub repository.