如何在Kubernetes集群用Traefik Ingress Controller实现自定义前后端流量路由
Got it, let's break down exactly how to set up Traefik as your Kubernetes Ingress Controller to work with your custom auth frontend and backend app. I’ll walk you through a step-by-step solution that fits your request flow perfectly:
First, let’s make sure we have the basics covered:
- Traefik is already deployed in your Kubernetes cluster (I recommend using the CRD mode since it’s way more flexible for custom routing rules)
- Your custom auth frontend service is running in K8s, with a Service named
auth-frontend-svcexposed on port 80 - Your backend app service is deployed, with a Service named
app-backend-svcexposed on port 80, handling requests at the/apppath
We’ll need two middlewares here: one to redirect unauthenticated users to your auth frontend, and another to validate authentication before forwarding requests to the backend.
Middleware 1: Redirect to Auth Frontend
This middleware will catch unauthenticated requests to /app and redirect users to your auth frontend, preserving the original request URL as a callback parameter so users can be sent back after logging in:
apiVersion: traefik.containo.us/v1alpha1 kind: Middleware metadata: name: redirect-to-auth spec: redirectRegex: regex: ^https?://a\.b\.c\.com/app(.*) replacement: http://a.b.c.com/auth?redirect=$${0} permanent: false
Middleware 2: Validate Authentication
This ForwardAuth middleware tells Traefik to check with your auth frontend’s validation API before letting requests through to the backend. Your frontend will return a 200 if the user is authenticated, or a 401 if not (which triggers the redirect middleware):
apiVersion: traefik.containo.us/v1alpha1 kind: Middleware metadata: name: auth-check spec: forwardAuth: address: http://auth-frontend-svc.default.svc.cluster.local/api/check-auth authResponseHeaders: - X-User-Id - X-User-Role trustForwardHeader: true
Note: Replace default with your auth frontend’s namespace if it’s not in the default one. The authResponseHeaders lets you pass user context (like user ID or role) from your auth frontend to the backend.
Now we’ll create two IngressRoutes: one for your auth frontend, and one for your backend app that uses the middlewares we just created.
IngressRoute for Auth Frontend
This routes all /auth traffic directly to your custom frontend:
apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: auth-frontend-route spec: entryPoints: - web routes: - match: Host(`a.b.c.com`) && PathPrefix(`/auth`) kind: Rule services: - name: auth-frontend-svc port: 80
IngressRoute for Backend App
This routes /app traffic, but only after authentication is validated:
apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: app-backend-route spec: entryPoints: - web routes: - match: Host(`a.b.c.com`) && PathPrefix(`/app`) kind: Rule middlewares: - name: auth-check - name: redirect-to-auth services: - name: app-backend-svc port: 80
Your custom frontend needs to handle a few key things to make this flow work:
- When users land on
/auth?redirect=<original-request-url>, display your login page - After successful login, set a secure, HttpOnly authentication cookie (e.g.,
auth-token) and redirect the user back to the URL in theredirectparameter - Implement the
/api/check-authendpoint:- Check if the incoming request has a valid
auth-tokencookie - If valid, return a 200 status code (you can add user info headers here if needed)
- If invalid, return a 401 status code
- Check if the incoming request has a valid
Let’s walk through the end-to-end process to confirm it matches your request:
- A client sends a request to
http://a.b.c.com/app?params=bla - Traefik matches the
app-backend-routeand runs theauth-checkmiddleware, sending a request to your frontend’s/api/check-auth - Your frontend sees no valid auth cookie, returns a 401
- Traefik triggers the
redirect-to-authmiddleware, sending the user tohttp://a.b.c.com/auth?redirect=http://a.b.c.com/app?params=bla - The user logs in successfully, your frontend sets the auth cookie and redirects back to the original
/apprequest - The client resends the
/apprequest, now with the auth cookie - Traefik runs
auth-checkagain, your frontend returns 200 (authenticated) - Traefik forwards the request to your
app-backend-svcfor processing
- Switch to HTTPS (configure Traefik with TLS certificates) to keep auth cookies secure (set the
Secureflag on your cookie too) - If you’re using a cluster-wide Traefik deployment, make sure your middlewares and ingress routes are in the same namespace as your services, or reference them with fully qualified names
- You can add rate limiting or IP whitelisting middlewares to your auth frontend route to prevent brute-force attacks
内容的提问来源于stack exchange,提问作者Valentin

