nginx的502报错和504报错有什么区别?
引入
还真是个无聊的话题,不过这是一个面试题。考察你对Nginx工作机制的了解。
分析
我们先来看维基百科上的解释:
502 Bad Gateway
The server was acting as a gateway or proxy and received an invalid response from the upstream server.
504 Gateway Timeout
The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.
好了,看完解释,答案也出来了。
502指的是后端服务器无响应,压根没收到有效的反馈。
504指的是后端服务器没有及时响应,也就是说期待某个回应,但等待时间过长,超时
模拟一个nginx504报错
php代码:
<?php
echo date('h:i:s') . "<br />";
//暂停 10 秒
sleep(40);
//重新开始
echo date('h:i:s');
?>
nginx配置
location / {
proxy_pass http://php;
proxy_connect_timeout 30;
proxy_send_timeout 30;
proxy_read_timeout 30;
}
结果:
[root@BJ-BX-130-27 ~]#time curl -H "Host:ipcpu.com" http://127.0.0.1/testphp.php
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>504 Gateway Time-out</title></head>
<body bgcolor="white">
<h1>504 Gateway Time-out</h1>
<p>The gateway did not receive a timely response from the upstream server or application. Sorry for the inconvenience.<br/>
Please report this message and include the following information to us.<br/>
Thank you very much!</p>
<table>
此处省略……
real 0m30.005s
user 0m0.001s
sys 0m0.004s
模拟nginx502错误
nginx配置
proxy_pass http://10.127.130.41:8900;
#nginx和后端upstream无法通信
结果:
[root@BJ-BX-130-27 ~]#time curl -H "Host:ipcpu.com" http://127.0.0.1/
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<h1>502 Bad Gateway</h1>
<p>The proxy server received an invalid response from an upstream server. Sorry for the inconvenience.<br/>
Please report this message and include the following information to us.<br/>
Thank you very much!</p>
<table>
此处省略……
real 0m3.006s
user 0m0.002s
sys 0m0.002s
结论
通过上面两个实验,是不是更清晰了?
通俗一些,502是后端死了,连不上(可能无法建立TCP连接) ,504是后端活着,但没给我回应(至少TCP连接已经建立)。
如何解除错误
502的情况需要检查后端服务器状态。
504的情况需要检查后端服务器响应情况,和nginx设置的超时时间。
参考资料
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
转载请注明:IPCPU-网络之路 » nginx的502报错和504报错有什么区别