使用 Nginx 容器为 Traefik 配置高性能通用错误页面

2023-10-14 15:40

本文主要是介绍使用 Nginx 容器为 Traefik 配置高性能通用错误页面,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

使用 Traefik 比较久的读者应该会发现,在服务重启的时候,原来的网站会展示 404 not found 的空白页面,虽然多数情况下服务恢复很快,但是这个恢复时间取决于部署启动的应用和监控检查配置策略,如果没有配置流量切换规则,那么有的时候,会看到很久的空白页面,这样的体验显然不好。

为了提升体验,我们可以使用 Traefik 提供的错误页面中间件来解决这个问题,优化访问体验。本篇思路同样可以处理通用 Nginx 错误页面的创建。

如何使用 Traefik 错误页中间件

虽然官方文档中有明确记录“错误页面”中间件的使用方法:

labels:- "traefik.http.middlewares.test-errorpage.errors.status=500-599"- "traefik.http.middlewares.test-errorpage.errors.service=serviceError"- "traefik.http.middlewares.test-errorpage.errors.query=/{status}.html"

但是这只描述了如何使用中间件,我们还需要实际的“应用服务”来支持在错误发生的时候,能够有对应的错误页面展示给用户,所以处理这段逻辑对应的配置如下:

labels:- "traefik.enable=true"- "traefik.docker.network=traefik"# 定义中间件- "traefik.http.middlewares.error-pages-middleware.errors.status=400-599"- "traefik.http.middlewares.error-pages-middleware.errors.service=error-pages-service"- "traefik.http.middlewares.error-pages-middleware.errors.query=/{status}.html"# 使用中间件- "traefik.http.routers.error-pages-router.middlewares=error-pages-middleware@docker"- "traefik.http.routers.errorpage.entrypoints=https"- "traefik.http.routers.errorpage.tls=true"- "traefik.http.routers.errorpage.rule=HostRegexp(`{host:.+}`)"- "traefik.http.routers.errorpage.priority=1"- "traefik.http.services.error-pages-service.loadbalancer.server.port=80"

在进行配置的时候,还需要注意一个细节:

labels:- "traefik.http.routers.errorpage.priority=1"

我们务必降低这个服务的优先级,避免影响业务正常运行。这样才能保证在其他业务中断的时候,展示这个页面,而非遇到一些极端情况下的时候,我们看到的不是预期中的内容。

另外,如果不希望准备多个错误页面的话,可以考虑将 {status}.html 改为指定的固定页面 index.html:

labels:- "traefik.http.middlewares.error-pages-middleware.errors.query=/index.html"

寻找HTTP错误码页面相关的开源项目

在配置书写完毕之后,我们需要准备对应的错误页面,我们都知道常用的 HTTP 错误码有至少20个,所以如果依赖人工来处理,非常不利于维护。

考虑到现在 traefik 用户量不少了,应该有人有类似需求,经过搜索果然找到了国外小哥编写的项目:github.com/tarampampam/

简单使用这个开源项目,感觉还好,但是如果你想定制页面的话,需要准备的内容稍微有一些多:

  • 依赖一个页面生成工具,构建 Node 构建镜像。
  • 依赖自定义的 Nginx docker-entrypoint.sh,并需要构建 Nginx 运行镜像,以及需要修改默认的 Nginx.conf。

追求简洁高效是工程师的基础素养,所以我们能否有更简单的方案呢?

使用官方 Nginx 镜像进行定制

我们知道 Nginx 在 1.18 之后提供了一个特殊功能,允许用户自定义及额外的扩展 docker-entrypoint.d 脚本,以及支持使用基于 envsubst 的自定义 Nginx 配置文件而不需要修改官方镜像中的 nginx.conf 和 docker-entrypoint.sh 文件。

稍微扩展一些思路,不难想到可以使用 envsubst 以及 扩展的 docker-entrypoint.d 来进行自定义页面的预处理。

出于分发性能考虑,我们使用 alpine 版本的 Nginx Docker 容器镜像。

编写模版页面

出于演示,这里简化我们的模版结构,仅演示如何使用 envsubst 来完成需求:

<html lang="en-US">
<head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><title>${DEFAULT_CODE} ${DEFAULT_TITLE}</title>
</head>
<body><h1>${DEFAULT_TITLE}</h1><p>${DEFAULT_DESC}</p>
</body>
</html>

在页面中定义需要使用的数据变量后,便可以着手准备页面内的数据了。

准备错误码列表数据

准备数据的时候,考虑计划使用 shell 来进行处理,shell 默认对 JSON 处理支持能力不佳,所以这里需要将错误码进行整理,最好整理为一行几列的模式,方便程序读取和解析。

因为描述文本在后续调整更新过程中,潜在会引入逗号,所以这里使用分号作为分隔符,避免潜在问题:

400;Bad Request;The server did not understand the request
401;Unauthorized;The requested page needs a username and a password
403;Forbidden;Access is forbidden to the requested page
404;Not Found;The server can not find the requested page
405;Method Not Allowed;The method specified in the request is not allowed
407;Proxy Authentication Required;You must authenticate with a proxy server before this request can be served
408;Request Timeout;The request took longer than the server was prepared to wait
409;Conflict;The request could not be completed because of a conflict
410;Gone;The requested page is no longer available
411;Length Required;The "Content-Length" is not defined. The server will not accept the request without it
412;Precondition Failed;The pre condition given in the request evaluated to false by the server
413;Payload Too Large;The server will not accept the request, because the request entity is too large
416;Requested Range Not Satisfiable;The requested byte range is not available and is out of bounds
418;I'm a teapot;Attempt to brew coffee with a teapot is not supported
429;Too Many Requests;Too many requests in a given amount of time
500;Internal Server Error;The server met an unexpected condition
502;Bad Gateway;The server received an invalid response from the upstream server
503;Service Unavailable;The server is temporarily overloading or down
504;Gateway Timeout;The gateway has timed out
505;HTTP Version Not Supported;The server does not support the "http protocol" version

将上面的内容保存为 pages.csv 后,继续编写数据解析脚本。

编写解析脚本

因为我们预期使用 alpine 版本的镜像,镜像内默认只有 sh,所以这里编写功能的时候,不能使用 array 拆分的方式,需要进行变通:

cat "pages.csv" | grep ";" | while read line; doCODE=$(echo "$line" | cut -d";" -f1)TITLE=$(echo "$line" | cut -d";" -f2)DESC=$(echo "$line" | cut -d";" -f3)echo $CODE;echo $TITLE;echo $DESC;
done

执行脚本进行验证,可以看到解析结果是符合预期的:

400
Bad Request
The server did not understand the request
401
Unauthorized
The requested page needs a username and a password
403
Forbidden
Access is forbidden to the requested page
...

核心功能编写完毕,接下来是站在“巨人的肩膀”上,参考官方镜像的脚本,实现“自动读取数据生成各种错误码页面”。

编写模版生成脚本

官方容器中用于生成 nginx 配置的 “docker-entrypoint.d/20-envsubst-on-templates.sh” 脚本是这样编写的:

#!/bin/shset -eME=$(basename $0)auto_envsubst() {local template_dir="${NGINX_ENVSUBST_TEMPLATE_DIR:-/etc/nginx/templates}"local suffix="${NGINX_ENVSUBST_TEMPLATE_SUFFIX:-.template}"local output_dir="${NGINX_ENVSUBST_OUTPUT_DIR:-/etc/nginx/conf.d}"local template defined_envs relative_path output_path subdirdefined_envs=$(printf '${%s} ' $(env | cut -d= -f1))[ -d "$template_dir" ] || return 0if [ ! -w "$output_dir" ]; thenecho >&3 "$ME: ERROR: $template_dir exists, but $output_dir is not writable"return 0fifind "$template_dir" -follow -type f -name "*$suffix" -print | while read -r template; dorelative_path="${template#$template_dir/}"output_path="$output_dir/${relative_path%$suffix}"subdir=$(dirname "$relative_path")# create a subdirectory where the template file existsmkdir -p "$output_dir/$subdir"echo >&3 "$ME: Running envsubst on $template to $output_path"envsubst "$defined_envs" < "$template" > "$output_path"done
}auto_envsubstexit 0

可以看到思路还是比较清晰的,我们将前文中的解析脚本和这段脚本适当合并,来完成我们的需求。

#!/bin/shset -eME=$(basename $0)auto_envsubst() {local template_dir="${ERRORPAGE_ENVSUBST_TEMPLATE_DIR:-/pages}"local suffix="${ERRORPAGE_ENVSUBST_TEMPLATE_SUFFIX:-.html}"local output_dir="${ERRORPAGE_ENVSUBST_OUTPUT_DIR:-/usr/share/nginx/html}"local template defined_envs relative_path output_path subdirdefined_envs=$(printf '${%s} ' $(env | cut -d= -f1))[ -d "$template_dir" ] || return 0if [ ! -w "$output_dir" ]; thenecho >&3 "$ME: ERROR: $template_dir exists, but $output_dir is not writable"return 0fifind "$template_dir" -follow -type f -name "*$suffix" -print | while read -r template; dorelative_path="${template#$template_dir/}"output_path="$output_dir/${relative_path%$suffix}$suffix"subdir=$(dirname "$relative_path")# create a subdirectory where the template file existsmkdir -p "$output_dir/$subdir"echo >&3 "$ME: Running envsubst on $template to $output_path"envsubst "$defined_envs" < "$template" > "$output_path"sed -i "s/^[[:space:]\t\n]*//g" "$output_path"cat "${template_dir}/pages.csv" | grep ";" | while read line; doCODE=$(echo "$line" | cut -d";" -f1)TITLE=$(echo "$line" | cut -d";" -f2)DESC=$(echo "$line" | cut -d";" -f3)export DEFAULT_CODE=$CODEexport DEFAULT_TITLE=$TITLEexport DEFAULT_DESC=$DESCexport output_path="$output_dir/$CODE$suffix"envsubst "$defined_envs" < "$template" > "$output_path"donedone
}auto_envsubstexit 0

将内容保存为 30-envsubst-on-pages.sh,稍后使用。

编写 Nginx 配置

因为官方镜像支持扩展配置,所以我们无需修改主 Nginx.conf ,只需要根据需求书写新的配置即可:

server {listen        ${NGINX_PORT};server_name   ${NGINX_HOST};charset       utf-8;gzip on;access_log    off;log_not_found off;server_tokens off;location / {root   /usr/share/nginx/html;index  index.html;}error_page 400 /400.html;error_page 401 /401.html;error_page 403 /403.html;error_page 404 /404.html;error_page 405 /405.html;error_page 407 /407.html;error_page 408 /408.html;error_page 409 /409.html;error_page 410 /410.html;error_page 411 /411.html;error_page 412 /412.html;error_page 413 /413.html;error_page 416 /416.html;error_page 418 /418.html;error_page 429 /429.html;error_page 500 /500.html;error_page 502 /502.html;error_page 503 /503.html;error_page 504 /504.html;error_page 505 /505.html;location = /favicon.ico {add_header 'Content-Type' 'image/x-icon';return 200 "";}location = /robots.txt {return 200 "User-agent: *\nDisallow: /";}
}

将上面的内容保存为 default.conf.template,接下来完成容器配置,就可以使用这个服务啦。

编写服务容器配置

我们的容器配置文件其实很简单:

version: '3'services:errorpage-nginx:image: nginx:1.19.4-alpinevolumes:- ./templates:/etc/nginx/templates:ro- ./docker-entrypoint.d/30-envsubst-on-pages.sh:/docker-entrypoint.d/30-envsubst-on-pages.sh:ro- ./pages:/pages:roenvironment:- NGINX_HOST=localhost- NGINX_PORT=80- DEFAULT_CODE=404- DEFAULT_TITLE=The page you're looking for is now beyond our reach. Let's get you..- DEFAULT_DESC=Page not foundnetworks:- traefiklabels:- "traefik.enable=true"- "traefik.docker.network=traefik"- "traefik.http.routers.errorpage.entrypoints=https"- "traefik.http.routers.errorpage.tls=true"- "traefik.http.routers.errorpage.rule=HostRegexp(`{host:.+}`)"- "traefik.http.routers.errorpage.priority=1"- "traefik.http.services.error-pages-service.loadbalancer.server.port=80"- "traefik.http.routers.error-pages-router.middlewares=error-pages-middleware@docker"- "traefik.http.middlewares.error-pages-middleware.errors.status=400-599"- "traefik.http.middlewares.error-pages-middleware.errors.service=error-pages-service"- "traefik.http.middlewares.error-pages-middleware.errors.query=/{status}.html"networks:traefik:external: true

你或许会疑问,为什么还有三个默认环境变量 DEFAULT_CODE、DEFAULT_TITLE、DEFAULT_DESC,这些变量是用于处理服务站点首页 index.html 文件,如果你愿意的话,可以自由发挥整点不一样的内容。

最后


v2-59e896cb04fdfd06f1145821e0915027_b.jpg
我使用的错误页面模版

不得不说,新版本的 Nginx 容器镜像相当强大,从历史文章中也应该看的出我对它的喜欢:小巧、简洁、高性能、接口丰富。如果你还在使用老版本的 Nginx ,不妨考虑升级到最新版本。

这篇关于使用 Nginx 容器为 Traefik 配置高性能通用错误页面的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/211478

相关文章

postgresql使用UUID函数的方法

《postgresql使用UUID函数的方法》本文给大家介绍postgresql使用UUID函数的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录PostgreSQL有两种生成uuid的方法。可以先通过sql查看是否已安装扩展函数,和可以安装的扩展函数

Spring Boot Maven 插件如何构建可执行 JAR 的核心配置

《SpringBootMaven插件如何构建可执行JAR的核心配置》SpringBoot核心Maven插件,用于生成可执行JAR/WAR,内置服务器简化部署,支持热部署、多环境配置及依赖管理... 目录前言一、插件的核心功能与目标1.1 插件的定位1.2 插件的 Goals(目标)1.3 插件定位1.4 核

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

MySQL中比较运算符的具体使用

《MySQL中比较运算符的具体使用》本文介绍了SQL中常用的符号类型和非符号类型运算符,符号类型运算符包括等于(=)、安全等于(=)、不等于(/!=)、大小比较(,=,,=)等,感兴趣的可以了解一下... 目录符号类型运算符1. 等于运算符=2. 安全等于运算符<=>3. 不等于运算符<>或!=4. 小于运

使用zip4j实现Java中的ZIP文件加密压缩的操作方法

《使用zip4j实现Java中的ZIP文件加密压缩的操作方法》本文介绍如何通过Maven集成zip4j1.3.2库创建带密码保护的ZIP文件,涵盖依赖配置、代码示例及加密原理,确保数据安全性,感兴趣的... 目录1. zip4j库介绍和版本1.1 zip4j库概述1.2 zip4j的版本演变1.3 zip4

RabbitMQ消息总线方式刷新配置服务全过程

《RabbitMQ消息总线方式刷新配置服务全过程》SpringCloudBus通过消息总线与MQ实现微服务配置统一刷新,结合GitWebhooks自动触发更新,避免手动重启,提升效率与可靠性,适用于配... 目录前言介绍环境准备代码示例测试验证总结前言介绍在微服务架构中,为了更方便的向微服务实例广播消息,

Python 字典 (Dictionary)使用详解

《Python字典(Dictionary)使用详解》字典是python中最重要,最常用的数据结构之一,它提供了高效的键值对存储和查找能力,:本文主要介绍Python字典(Dictionary)... 目录字典1.基本特性2.创建字典3.访问元素4.修改字典5.删除元素6.字典遍历7.字典的高级特性默认字典

使用Python构建一个高效的日志处理系统

《使用Python构建一个高效的日志处理系统》这篇文章主要为大家详细讲解了如何使用Python开发一个专业的日志分析工具,能够自动化处理、分析和可视化各类日志文件,大幅提升运维效率,需要的可以了解下... 目录环境准备工具功能概述完整代码实现代码深度解析1. 类设计与初始化2. 日志解析核心逻辑3. 文件处

Nginx安全防护的多种方法

《Nginx安全防护的多种方法》在生产环境中,需要隐藏Nginx的版本号,以避免泄漏Nginx的版本,使攻击者不能针对特定版本进行攻击,下面就来介绍一下Nginx安全防护的方法,感兴趣的可以了解一下... 目录核心安全配置1.编译安装 Nginx2.隐藏版本号3.限制危险请求方法4.请求限制(CC攻击防御)

nginx中端口无权限的问题解决

《nginx中端口无权限的问题解决》当Nginx日志报错bind()to80failed(13:Permissiondenied)时,这通常是由于权限不足导致Nginx无法绑定到80端口,下面就来... 目录一、问题原因分析二、解决方案1. 以 root 权限运行 Nginx(不推荐)2. 为 Nginx