nginx 502 和 504 超时演示

您所在的位置:网站首页 502坏网关-无法连接到上游服务器 nginx 502 和 504 超时演示

nginx 502 和 504 超时演示

2023-09-02 02:55| 来源: 网络整理| 查看: 265

原链接

最近线上 nginx 遇到了一些较难排查的 502 和 504 错误,顺便了解了一下 nginx 的相关配置。我发现网上很多介绍 nginx 超时配置只是列了这几个配置的含义和数值,并没有解释什么原因会触发哪个配置。因此趁这个机会演示一下,如何让 nginx 符合预期正确出现 502 和 504。

502 和 504 的解释

在 http status 的 定义 中:

502 Bad Gateway: The server was acting as a gateway or proxy and received an invalid response from the upstream server. 504: he server was acting as a gateway or proxy and did not receive a timely response from the upstream server.

502 的错误原因是 Bad Gateway,一般是由于上游服务的故障引起的;而 504 则是 nginx 访问上游服务超时,二者完全是两个意思。但在某些情况下,上游服务的超时(触发 tcp reset)也可能引发 502,我们会在之后详述。

演示环境

你需要 3 个逻辑组件:nginx 服务器,php-fpm,client 访问客户端。3 个组件可以在同一台机器中,我用的是 docker 来配置 PHP 和 nginx 环境,在宿主机上访问。如果你很熟悉这 3 个组件,这部分可以跳过。用 docker 来做各种测试和实验非常方便,这里就不展开了。docker-compose 的配置参考了这篇文章。我的 docker composer 文件如下:

version: '3' services: web: image: nginx:alpine ports: - "8080:80" volumes: - ./code:/code - ./nginx/site.conf:/etc/nginx/conf.d/site.conf depends_on: - php php: image: php:7.1-fpm-alpine volumes: - ./code:/code - ./php/php-fpm.conf:/usr/local/etc/php-fpm.conf

使用的镜像都是基于 alpine 制作的,非常小巧:

REPOSITORY TAG SIZE php 7.1-fpm-alpin 69.5MB nginx alpine 18.6MB

nginx 的配置:

server { index index.php index.html; server_name php-docker.local; error_log /var/log/nginx/error.log; access_log /var/log/nginx/access.log; root /code; location ~ \.php$ { try_files $uri =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param PATH_INFO $fastcgi_path_info; fastcgi_connect_timeout 5s; fastcgi_read_timeout 8s; fastcgi_send_timeout 10s; } }

php-fpm 的配置

[global] include=etc/php-fpm.d/*.conf request_terminate_timeout=3s

代码放在 github。

关键参数

在这个演示中,PHP 的关键参数有两个,一个是 PHP 脚本的 max_execution_time,这个配置在php.ini中;另一个是 php-fpm 的 request_terminate_timeout,在php-fpm.conf中。当以 php-fpm 提供服务时,request_terminate_timeout 设置会覆盖 max_execution_time 的设置,因此我们这里只测试 request_terminate_timeout。

request_terminate_timeout 的意思是 php-fpm 接受的请求的超时时间,超过这个时间 php-fpm 会 kill 掉执行脚本的 worker 进程。

nginx的关键参数是 fastcgi 相关的 timeout,即:fastcgi_connect_timeout,fastcgi_read_timeout,fastcgi_send_timeout。

这几个 nginx 参数的主语都是 nginx,所以 fastcgi_connect_timeout 的意思是 nginx 连接到 fastcgi 的超时时间,fastcgi_read_timeout 是 nginx 读取 fastcgi 的内容的超时时间,fastcgi_send_timeout 是 nginx 发送内容到 fastcgi 的超时时间。

演示过程

首先启动 nginx 和 PHP:

docker-compose up

在 code 文件夹下添加一个 index.php 文件:



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3