You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask+UWSGI+Nginx环境下非根路径请求出现504超时问题求助

排查Nginx反向代理下/search/路由504超时问题

这种Nginx反向代理导致的504网关超时问题我碰到过好多次,结合你说的直接运行python3 app.py或uwsgi --socket 0.0.0.0:8080 --protocol=http -w run:app都能正常工作的情况,问题肯定出在Nginx和后端服务的通信环节,咱们一步步来定位:

1. 先确认Nginx反向代理配置是否正确

这是新手最容易踩坑的点,一定要搞清楚proxy_pass和uwsgi_pass的使用场景:

  • 如果你用的是带--protocol=http的uwsgi启动方式(也就是uwsgi以HTTP协议提供服务),Nginx里必须用proxy_pass指向uwsgi的地址,不能用uwsgi_pass
  • 给你一个参考的正确配置示例:
server {
    listen 80;
    server_name your_domain_or_ip;

    # 根路径基础配置
    location / {
        proxy_pass http://localhost:8080;
        # 这些请求头必须设置,否则后端可能无法正确识别请求来源
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    # 针对/search/的单独配置(如果根路径覆盖不够的话)
    location /search/ {
        proxy_pass http://localhost:8080/search/;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        
        # 重点!504大概率是超时导致的,这里调大超时时间
        proxy_connect_timeout 60s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}
  • 如果你用的是uwsgi的socket文件模式(比如uwsgi --socket /tmp/uwsgi.sock ...),那Nginx里要换成uwsgi_pass unix:/tmp/uwsgi.sock;,同时要确保Nginx进程(一般是www-data用户)有访问这个socket文件的权限,比如执行sudo chown www-data:www-data /tmp/uwsgi.sock

2. 检查Nginx的超时设置

504错误的核心就是Nginx等待后端响应的时间超过了默认阈值,默认的proxy_read_timeout一般是60秒,如果你的/search/接口需要处理大量数据、耗时较长,就需要调大这个值,比如改成120秒甚至更久,把配置放在对应的location块或者server块里都可以。

3. 查看日志找具体线索

光靠猜测效率太低,直接看日志能快速定位问题:

  • Nginx错误日志:一般在/var/log/nginx/error.log,看看里面有没有类似upstream timed out或者connection refused的报错,这些能直接告诉你是连接不上后端还是超时了
  • uwsgi日志:启动uwsgi的时候加--logto /var/log/uwsgi/app.log参数,生成日志后看看有没有收到/search/的请求,或者处理请求时有没有抛出异常

4. 排查防火墙/SELinux的拦截

Linux服务器上的安全机制经常会悄悄拦截通信:

  • 临时关闭SELinux测试:执行sudo setenforce 0,如果问题解决了,说明是SELinux阻止了Nginx访问后端服务,之后再配置SELinux规则允许通信就行
  • 防火墙检查:如果用的是ufw,执行sudo ufw allow 8080确保端口开放;如果是firewalld,执行sudo firewall-cmd --add-port=8080/tcp --permanent再重载规则sudo firewall-cmd --reload

5. 调整uwsgi的进程配置

如果你的/search/请求比较耗费资源,uwsgi的worker进程太少可能导致处理不过来,启动uwsgi的时候可以加--processes 4 --threads 2来增加进程和线程数,提升并发处理能力。

最后,改完任何配置后,记得重启Nginx和uwsgi:

  • 重启Nginx:sudo systemctl restart nginx
  • 重启uwsgi:如果启动时加了--pidfile /tmp/uwsgi.pid,可以用uwsgi --stop /tmp/uwsgi.pid停止,再重新启动;或者直接杀掉uwsgi进程再重启。

内容的提问来源于stack exchange,提问作者tubadc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:29:20