nginx - 经历 nginx 代理传递的随机超时
问题描述
这几天我一直在和这个问题作斗争。我找到了一个临时解决方案,但无法理解到底发生了什么。
因此,会立即处理一个请求。如果我在“等待”60 秒后立即发送相同的请求。如果我取消请求并发送新请求,则会再次正确处理。如果我在此之后发送请求,它会再次挂起。这个循环重复。这听起来像是一个负载平衡问题,但我没有设置它。nginx 是否有某种默认的负载平衡来连接上游服务器?
收到的错误是上游超时(110:连接超时)。
我发现更改这些代理参数后,它只会挂起 3 秒,并且每个后续请求现在都可以正常处理(在等待的请求之后)。我想是因为工作保持连接。
proxy_connect_timeout 3s;
看起来建立与上游的连接正在超时,然后在超时后再次尝试并成功。同样在上述“(取消)请求 - 确定请求 - (取消)请求”循环中,没有设置保持活动状态。只有当我等待请求完成时。没有上述设置需要 60 秒,这是不可接受的。
它发生在两个域..
NGINX 配置:
worker_processes 1;
events
{
worker_connections 1024;
}
http
{
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
gzip on;
# Timeouts
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
include /etc/nginx/mime.types;
default_type application/octet-stream;
include /etc/nginx/conf.d/*.conf;
server
{
server_name domain.com www.domain.com;
root /usr/share/nginx/html;
index index.html index.htm;
location /api/
{
proxy_redirect off;
proxy_pass http://localhost:3001/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
#TEMP fix
proxy_connect_timeout 3s;
}
}
DOMAIN2 配置:
server {
server_name domain2.com www.domain2.com;
location /api/
{
proxy_redirect off;
proxy_pass http://localhost:5000/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
#TEMP fix
proxy_connect_timeout 3s;
}
}
解决方案
我找到了答案。但是,我仍然不完全理解为什么以及如何。我怀疑设置keep-alive没有正常工作。我阅读了文档并在那里找到了答案:https ://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive
对于这两个配置文件,我添加了一个“上游”块。
IE
域2.CONF:
upstream backend
{
server 127.0.0.1:5000;
keepalive 16;
}
location /api/
{
proxy_redirect off;
proxy_pass http://backend/;
proxy_http_version 1.1;
proxy_set_header Connection "";
...
# REMOVED THE TEMP FIX
}
确保:
- 清除连接头
- 在上游块中使用 127.0.0.1 而不是 localhost
- 将http版本设置为1.1
推荐阅读
- javascript - 为什么我会得到“引用前一个状态时在 setState 中使用回调”?
- amazon-web-services - redshift 中是否有任何系统表可以提供我创建的库对象的所有属性
- reactjs - React Link更改URL但仅在单击下拉菜单中的列表项时渲染一次组件
- postgresql - 我的查询没有获取创建的索引
- google-chrome-extension - 弹出菜单未打开
- php - 如何监听 Trait 中所有可用的 Laravel 模型事件
- function - Haskell 对水平线感到困惑
- c - 如何使用C中的护士从下到上而不是从上到下画线
- c++ - 矩形上的最小切割以制成正方形
- c# - 如何实现 getBit 和 setBit 方法?