前言
有些时候我们不想使用Nginx-ingress的默认的404错误页面,或者我们想在后端service不可用的时候不暴露给客户端nginx 503 Service Temporarily Unavailable 的页面,那怎么办?Nginx-ingress 提供了Custom errors来帮我们解决.
创建测试应用
我们这里使用go语言谢了一个小应用,以80端口暴露一个api来提供访问测试,将它打包成镜像,然后上传至docker hub
1 | package main |
1 | ARG APPLICATION=webserver |
使用我们打包好的镜像部署一个deployment,service暴露containerPort给ingress
1 | $ kubectl create deployment --image chulinx/echo-webserver:v1 webserver --port 80 -n cepni |
创建ingress 暴露服务
1 | apiVersion: extensions/v1beta1 |
访问测试,没有问题的话我们可以得到一个api接口相应
1 | $ curl -s http://webserver.chulinx.cn/ | jq |
故意访问一个不存在的接口,我们看返回什么
1
2 $ curl -s http://webserver.chulinx.cn/v1
404 page not found
现在我们的目标就是改造这个错误,让这个错误显示很优雅
配置ingress-nginx
- 自定义默认后端
顾名思义,就是将那些ingress规则找不到service的规则,都转发给默认后端服务,第一步我们要创建默认后端服务
1 | $ kubectl create deployment custom-default-backend --image chulinx/ingressingresscustomerrorpage:v0.2 --port 80 -n ingress-nginx |
配置Ningx-ingress的–default-backend-service
1 | spec: |
- 配置ingress-nginx ConfigMap ingress-nginx-controller
增加custom-http-errors: 404,413,503,意思是说,404,503,413状态的请求都由我们自定义的后端服务返回请求内容
1 | apiVersion: v1 |
访问测试
- 正常访问服务
- 访问一个不存在的域名
我们访问一个域名指向k8s节点的url,ingress规则中没有对此url做规则设置,正常会出现404 page not found,现在我们要访问出现我们自定义的404页面
- 访问故障服务
把webserver deployment 的服务删除掉,模拟服务端500错误
- 本文作者: ChuLinx
- 本文链接: http://yoursite.com/2020/09/18/ingress-Nginx如何自定义错误页面/
- 版权声明: 本博客所有文章除特别声明外,均采用 MIT 许可协议。转载请注明出处!