我在为后端服务设置路径入口控制器时遇到问题。例如,我要设置:
NodeJS:Index.js
const express = require('express')
const app = express()
const port = 4000
app.get('/', (req, res) => res.send('Welcome to myApp!'))
app.use('/data/office', require('./roffice'));
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
另一条路线:roffice.js
var express = require('express')
var router = express.Router()
router.get('/getOffice', async function (req, res) {
res.send('Get Data Office')
});
module.exports = router
Deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: ws-stack
spec:
selector:
matchLabels:
run: ws-stack
replicas: 2
template:
metadata:
labels:
run: ws-stack
spec:
containers:
- name: ws-stack
image: wsstack/node/img
imagePullPolicy: IfNotPresent
ports:
- containerPort: 4000
Service.yaml
apiVersion: v1
kind: Service
metadata:
name: service-wsstack
labels:
run: service-wsstack
spec:
type: NodePort
ports:
- port: 80
protocol: TCP
nodePort: 30009
targetPort: 4000
selector:
run: ws-stack
ingress.yaml
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: stack-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /
nginx.ingress.kubernetes.io/use-regex: "true"
spec:
rules:
- host: hello-world.info
- http:
paths:
- path: /
backend:
serviceName: service-ngstack --> frondend
servicePort: 80
- path: /webservice
backend:
serviceName: service-wsstack --> backend
servicePort: 80
i成功设置了部署,服务和入口。但是当我打电话给curl
curl http://<minikubeip>/webservice --> Welcome to myApp! => Correct
curl http://<minikubeip>/webservice/data/office/getOffice --> Welcome to myApp! => Not correct
如果我呼叫了另一条路由,结果将是相同的“欢迎使用myApp”。但是,如果我使用Nodeport
curl http://<minikubeip>:30009/data/office/getOffice => 'Get Data Office', working properly.
出什么问题了?有什么办法吗?谢谢
答案 0 :(得分:1)
nginx.ingress.kubernetes.io/rewrite-target: /$2
path: /webservice($|/)(.*)
问题出在您进入的那一行:
nginx.ingress.kubernetes.io/rewrite-target: /
您要告诉nginx将您的网址重写为/
,无论匹配什么。
/webservice
=> /
/webservice/data/office/getOffice
=> /
要执行的操作使用正则表达式,这是一个简单的示例:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: stack-ingress
annotations:
nginx.ingress.kubernetes.io/rewrite-target: /$2
nginx.ingress.kubernetes.io/use-regex: "true"
spec:
rules:
- host: hello-world.info
- http:
paths:
- path: /
backend:
serviceName: service-ngstack --> frondend
servicePort: 80
- path: /webservice($|/)(.*)
backend:
serviceName: service-wsstack --> backend
servicePort: 80
这样,您要让nginx用第二个匹配组重写您的URL。 最后,它会给您:
/webservice
=> /
/webservice/data/office/getOffice
=> /data/office/getOffice