最新消息:

nginx的502报错和504报错有什么区别

Linux ipcpu 5884浏览

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代码:

  1. <?php
  2. echo date('h:i:s') . "<br />";
  3. //暂停 10 秒
  4. sleep(40);
  5. //重新开始
  6. echo date('h:i:s');
  7. ?>

nginx配置

  1. location / {
  2. proxy_pass http://php;
  3. proxy_connect_timeout 30;
  4. proxy_send_timeout 30;
  5. proxy_read_timeout 30;
  6. }

结果:

  1. [root@BJ-BX-130-27 ~]#time curl -H "Host:ipcpu.com" http://127.0.0.1/testphp.php
  2. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
  3. <html>
  4. <head><title>504 Gateway Time-out</title></head>
  5. <body bgcolor="white">
  6. <h1>504 Gateway Time-out</h1>
  7. <p>The gateway did not receive a timely response from the upstream server or application. Sorry for the inconvenience.<br/>
  8. Please report this message and include the following information to us.<br/>
  9. Thank you very much!</p>
  10. <table>
  11. 此处省略……
  12. real 0m30.005s
  13. user 0m0.001s
  14. sys 0m0.004s

模拟nginx502错误

nginx配置

  1. proxy_pass http://10.127.130.41:8900;
  2. #nginx和后端upstream无法通信

结果:

  1. [root@BJ-BX-130-27 ~]#time curl -H "Host:ipcpu.com" http://127.0.0.1/
  2. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
  3. <html>
  4. <head><title>502 Bad Gateway</title></head>
  5. <body bgcolor="white">
  6. <h1>502 Bad Gateway</h1>
  7. <p>The proxy server received an invalid response from an upstream server. Sorry for the inconvenience.<br/>
  8. Please report this message and include the following information to us.<br/>
  9. Thank you very much!</p>
  10. <table>
  11. 此处省略……
  12. real 0m3.006s
  13. user 0m0.002s
  14. sys 0m0.002s

结论

通过上面两个实验,是不是更清晰了?
通俗一些,502是后端死了,连不上(可能无法建立TCP连接) ,504是后端活着,但没给我回应(至少TCP连接已经建立)。

如何解除错误

502的情况需要检查后端服务器状态。
504的情况需要检查后端服务器响应情况,和nginx设置的超时时间。

参考资料

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

转载请注明:IPCPU-网络之路 » nginx的502报错和504报错有什么区别