Kubernetes中Tomcat应用Ingress路径路由配置问题求助
解决方案
先修正配置里的明显错误
你的Ingress配置里servicePort写的是8080,但Service里暴露的端口是3000,这会导致Ingress无法正确转发流量到Service,先把Ingress里的servicePort改成3000。
核心问题:Tomcat应用上下文路径与Ingress路径不匹配
你的Tomcat里部署了SampleWebApp.war,默认情况下Tomcat会把war包名作为应用的上下文路径,所以实际访问路径是http://<tomcat-ip>:8080/SampleWebApp。而你设置Ingress路径为/tomcat,此时访问http://build.com/tomcat时,Ingress会把请求转发到Tomcat的/tomcat路径,但你的应用实际在/SampleWebApp路径下,所以会出现404无法访问的情况。
有两种常用解决方式:
方式一:通过Ingress做路径重写(推荐,无需修改Tomcat镜像)
如果用的是NGINX Ingress Controller,添加路径重写的annotation,把/tomcat/*的请求重写到/SampleWebApp/*。修改后的Ingress配置如下:
apiVersion: extensions/v1beta1 kind: Ingress metadata: name: tomcat namespace: tomcat annotations: nginx.ingress.kubernetes.io/rewrite-target: /SampleWebApp/$2 nginx.ingress.kubernetes.io/use-regex: "true" spec: rules: - host: build.com http: paths: - backend: serviceName: tomcat-service servicePort: 3000 path: /tomcat(/|$)(.*) pathType: ImplementationSpecific
解释:
nginx.ingress.kubernetes.io/rewrite-target:把匹配到的路径重写到/SampleWebApp/$2,$2对应path里(.*)捕获的内容path: /tomcat(/|$)(.*):匹配/tomcat、/tomcat/、/tomcat/xxx这类路径- 修正了
servicePort为3000,和Service的配置对齐
方式二:修改Tomcat应用的上下文路径
把SampleWebApp的上下文路径改成/tomcat,这样Ingress的路径就能直接对应。可以通过以下方式实现:
- 自定义Tomcat镜像:在镜像里创建
conf/Catalina/localhost/tomcat.xml文件,内容如下:
然后重新构建镜像,替换Deployment里的镜像地址。<Context docBase="/usr/local/tomcat/webapps/SampleWebApp.war" path="/tomcat"/> - 通过启动参数设置:在容器启动命令中添加Tomcat上下文路径参数,比如:
具体参数需根据你的Tomcat镜像调整。CATALINA_OPTS="-Dsamplewebapp.context.path=/tomcat"
修改后,Ingress配置只需修正servicePort即可:
apiVersion: extensions/v1beta1 kind: Ingress metadata: name: tomcat namespace: tomcat spec: rules: - host: build.com http: paths: - backend: serviceName: tomcat-service servicePort: 3000 path: /tomcat pathType: ImplementationSpecific
内容的提问来源于stack exchange,提问作者user3426197
相关产品推荐
相关产品推荐

