【问题标题】:How to improve nginx performance when I need to send multiple API requests in docker?当我需要在 docker 中发送多个 API 请求时,如何提高 nginx 性能?
【发布时间】:2021-09-25 09:29:05
【问题描述】:

我正在学习使用 nginx 在 docker compose 中连接服务器和应用程序。在应用程序中,我试图将数据发布到数据库并发送5 requests a time。 nginx 似乎对此不满意,然后我得到了502 错误:POST http://localhost/api/somerequest 502 (Bad Gateway)。如果我在1 request a time 使用较低的频率,它会起作用。

问题是是否有可能提高 nginx 性能以允许它处理多个大量请求,例如在5 request frequency。配置中有什么设置可以入手吗?

当前配置文件:

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

include conf.d/events.conf;
include conf.d/http.conf;

events {
    worker_connections 1024;
}

http {
    upstream server {
        server ${SERVER_HOST}:${SERVER_PORT}; # env variable from container
        keepalive 15;
    }

    upstream client {
        server ${CLIENT_HOST}:${CLIENT_PORT}; # env variable from container
        keepalive 15;
    }

    server {
        listen 80;
        server_name myservice; # my service container name in docker-compose.yml

        error_log   /var/log/nginx/myservice.error.log;
        access_log  /var/log/nginx/myservice.access.log;

        location / {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $http_host;

            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";

            proxy_set_header Connection "Keep-Alive";
            proxy_set_header Proxy-Connection "Keep-Alive";

            proxy_pass http://client;
        }

        location /api {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
            proxy_set_header Host $http_host;

            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";

            proxy_set_header Connection "Keep-Alive";
            proxy_set_header Proxy-Connection "Keep-Alive";

            proxy_pass http://server/api;
        }
    }
}

注意:nginx 容器中只有一个核心。我尝试将连接工作人员增加到4000,但它仍然不起作用。

提前谢谢你。

【问题讨论】:

  • Nginx 通常非常高效。如果您收到 HTTP 502 Bad Gateway 错误,则可能是后端服务没有足够快地产生响应,并且 Nginx 代理已决定它不可用。
  • 好的,谢谢您的信息。假设后端是固定的,是否可以让 nginx 等待响应避免中断?

标签: docker nginx docker-compose nginx-reverse-proxy nginx-config


【解决方案1】:

正如David 所说,nginx 通常非常高效。让 nginx 等待的神奇解决方案并不是真正的解决方案,除非您真的知道自己在做什么以及您面临的危险。

我想给你一个你想要的例子:

假设我们让 nginx 等待答案,或者如果失败,则等待一段时间。现在假设由于某种原因应用程序崩溃了几个小时。在那种情况下会发生什么?

更新(读取 cmets)

location / {
    echo_sleep 1;
    echo_exec @test;
}
location @test {
    echo $echo_request_uri;
}

【讨论】:

  • 感谢 ICIM。是否可以只增加一点等待时间?
  • 我希望更有说服力,这不是一个解决方案,但我看到你真的很感兴趣......我将代码留在答案中(向上)echo_sleep 1;。我建议您让所有请求等待几秒钟,从而强制所有请求。 (没有等待队列)
猜你喜欢
  • 2019-11-02
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-04
相关资源
最近更新 更多