一. Nginx Ingress 优雅显示谬误页面
官网
- 让所有通过 Nginx Ingress 裸露进来的域名,在申请到谬误页面的时候(状态码为:4xx,5xx 等)给用户一个优雅的页面显示,而不间接显示 4xx 或 5xx 的报错,防止给用户不好的应用体验
1. 镜像制作
- 将显示的页面全副放在 www 目录中
[root@yunwei-k8s-addon1-test custom-error]# ll www/
-rw-r--r--. 1 yeemiao yeemiao 415 3 月 13 2019 403.html
-rw-r--r--. 1 yeemiao yeemiao 412 3 月 13 2019 404.html
-rw-r--r--. 1 root root 412 8 月 16 13:40 500.html
-rw-r--r--. 1 root root 412 8 月 16 13:40 501.html
-rw-r--r--. 1 yeemiao yeemiao 415 3 月 13 2019 502.html
-rw-r--r--. 1 yeemiao yeemiao 409 3 月 13 2019 503.html
-rw-r--r--. 1 root root 412 8 月 16 13:40 504.html
# 目录构造
[root@yunwei-k8s-addon1-test custom-error]# ll
-rw-r--r--. 1 root root 72 8 月 16 13:37 Dockerfile
drwxr-xr-x. 2 root root 118 8 月 16 13:41 www
FROM registry.k8s.io/ingress-nginx/nginx-errors:v20230505
COPY www /www
2. nginx-error
- 放在和 Nginx-Ingress 控制器同样的名称空间中
apiVersion: v1
kind: Service
metadata:
name: nginx-errors
namespace: ingress-nginx
labels:
app.kubernetes.io/name: nginx-errors
app.kubernetes.io/part-of: ingress-nginx
spec:
selector:
app.kubernetes.io/name: nginx-errors
app.kubernetes.io/part-of: ingress-nginx
ports:
- port: 80
targetPort: 8080
name: http
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-errors
namespace: ingress-nginx
labels:
app.kubernetes.io/name: nginx-errors
app.kubernetes.io/part-of: ingress-nginx
spec:
replicas: 1
selector:
matchLabels:
app.kubernetes.io/name: nginx-errors
app.kubernetes.io/part-of: ingress-nginx
template:
metadata:
labels:
app.kubernetes.io/name: nginx-errors
app.kubernetes.io/part-of: ingress-nginx
spec:
containers:
- name: nginx-error-server
image: harbor.yeemiao.com:8443/library/custom-nginx-error:20230816
ports:
- containerPort: 8080
1). 配置
- 批改 Nginx-Ingress 的启动参数
# 退出参数,如果 nginx-error 和 Nginx-Ingress 在同一名称空间,间接退出参数即可,如果 nginx-error 服务不在 Nginx-Ingress 控制器同样的 Namespace,请将 POD_NAMESPACE 改为他所在的名称
- --default-backend-service=$(POD_NAMESPACE)/nginx-errors
# 批改 Nginx-Ingress 控制器的 configmap
[root@k8s-alone-1 manifest]# kubectl -n ingress-nginx edit cm nginx-configuration
apiVersion: v1
data:
allow-snippet-annotations: "true"
custom-http-errors: 403,404,413,500,501,502,503,504 # 减少这个配置
3. 验证
- 进入 nginx-ingress 的控制器查看 nginx 配置文件
/etc/nginx/nginx.conf
,过滤 error_page 是否有相干配置
error_page 403 = @custom_upstream-default-backend_403;
error_page 404 = @custom_upstream-default-backend_404;
error_page 413 = @custom_upstream-default-backend_413;
error_page 500 = @custom_upstream-default-backend_500;
error_page 502 = @custom_upstream-default-backend_502;
error_page 503 = @custom_upstream-default-backend_503;
error_page 504 = @custom_upstream-default-backend_504;