Kubernetes Ingress仅根路径/可用,多服务子路径配置404求助
Let's tackle your 404 issue and get your multi-service routing working as expected. There are two key problems with your current setup: incorrect rewrite rules in the Ingress configuration, and a misaligned port mapping in your Service.
1. The Rewrite Target Misconfiguration
Your current ingress.kubernetes.io/rewrite-target: / annotation tells the ingress controller to rewrite every matched path to the root (/). So when you access http://my.url.com/servicea/api/ping, the controller forwards the request to your service as / instead of /api/ping—which is why your service returns a 404 (it doesn't have an endpoint at the root).
To fix this, we need to use capturing groups in the path pattern to preserve the suffix of the URL after /servicea. We'll also use the modern ingress-nginx annotation (nginx.ingress.kubernetes.io/rewrite-target) for better compatibility.
Corrected Ingress Configuration
apiVersion: extensions/v1beta1 kind: Ingress metadata: name: boardingservice annotations: nginx.ingress.kubernetes.io/rewrite-target: /$2 spec: rules: - host: my.url.com http: paths: - path: /servicea(/|$)(.*) backend: serviceName: servicea-nodeport servicePort: 80 # Add paths for other services here (e.g., serviceb) - path: /serviceb(/|$)(.*) backend: serviceName: serviceb-nodeport servicePort: 80
How This Works:
- The path pattern
/servicea(/|$)(.*)matches:/servicea(exact match)/servicea/(trailing slash)/servicea/api/ping(and any other suffix)
- The
rewrite-target: /$2uses the second capturing group ((.*)) to forward only the suffix to your service. Sohttp://my.url.com/servicea/api/pinggets rewritten to/api/pingwhen sent toservicea.
2. Misaligned Service Port Mapping
Looking at your Deployment and Service configurations:
- Your
serviceacontainer exposes port8080 - Your Service
servicea-nodeportsetstargetPort: 8081, which points to theservicebcontainer in your Deployment
This means even if your ingress routing was correct, traffic would be sent to the wrong container! Fix the Service to point to servicea's actual port:
Corrected Service Configuration
apiVersion: v1 kind: Service metadata: name: servicea-nodeport spec: type: NodePort ports: - port: 80 targetPort: 8080 # Updated to match servicea's container port nodePort: 30124 selector: app: servicea
3. Apply and Test
- Apply the corrected configurations:
kubectl apply -f ingress.yaml kubectl apply -f service.yaml - Test the endpoint:
curl http://my.url.com/servicea/api/ping
This should now route correctly to your servicea container's /api/ping endpoint.
内容的提问来源于stack exchange,提问作者SME

