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

Nginx无法连接uWSGI求助:已成功安装但联动失败

Nginx与uWSGI联动出现504超时问题排查与解决

我看你现在遇到的是Nginx和uWSGI联动时的504网关超时错误,先梳理下你的配置和日志,然后直接说问题根源和解决办法:

你的配置与日志信息

Nginx配置(nginx.conf)

server {
    listen 80;
    server_name localhost;
    #charset koi8-r;
    charset utf-8;
    #access_log logs/host.access.log main;
    location / {
        include uwsgi_params;
        uwsgi_pass 127.0.0.1:8000;
        root html;
        index index.html index.htm;
    }
}

(注:你的配置里server块好像少了闭合的},记得补上,不然Nginx启动会报错)

uWSGI配置(uwsgi.ini)

http=127.0.0.1:8000
#socket=/root/project/learning_log/nginx_uwsgi.socket
chdir=/root/project/learning_log/
#chmod-socket=664
master=true
processes=4
threads=2
module=learning_log.wsgi
#wsgi-file=uwsgi_test.py
#stats=127.0.0.1:8000

启动命令

./nginx &
uwsgi3 --ini /root/project/learning_log/uwsgi.ini

日志信息

access.log
127.0.0.1 - - [15/Jan/2018:18:06:13 +0800] "GET / HTTP/1.1" 504 537 "-" "Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0"
error.log
2018/01/15 18:06:13 [error] 12986#0: *13 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 127.0.0.1, server: localhost, request: "GET / HTTP/1.1", upstream: "uwsgi://127.0.0.1:8000", host: "127.0.0.1"

问题根源

这问题其实很典型:你给uWSGI配置的是http协议端口(让uWSGI自己当HTTP服务器),但Nginx用uwsgi_pass时,是期望和uWSGI的uwsgi协议socket通信,两种协议不兼容,导致Nginx连不上uWSGI,最后超时抛出504错误。

解决步骤

1. 修改uWSGI配置,改用uwsgi协议socket

打开你的uwsgi.ini,把http参数换成socket(或者用unix socket,性能更好):

# 注释掉原来的http配置,改用uwsgi协议的socket端口
#http=127.0.0.1:8000
socket=127.0.0.1:8000
# 要是想用unix socket,就用下面这行(记得打开chmod-socket注释)
#socket=/root/project/learning_log/nginx_uwsgi.socket
chdir=/root/project/learning_log/
chmod-socket=664  # 打开这个注释,确保Nginx有权访问socket文件(unix socket模式下必须)
master=true
processes=4
threads=2
module=learning_log.wsgi

2. 调整Nginx配置(可选但推荐)

因为请求是转发给uWSGI处理的,Nginx的root html和index在这里没用,反而可能干扰,建议修改location块:

location / {
    include uwsgi_params;
    uwsgi_pass 127.0.0.1:8000;
    # 如果用unix socket,就改成下面这行
    #uwsgi_pass unix:/root/project/learning_log/nginx_uwsgi.socket;
}

另外别忘了补上server块末尾的},不然Nginx启动失败。

3. 重启服务,测试效果

先把之前的进程杀掉,再重新启动:

# 停止现有进程
pkill nginx
pkill uwsgi3
# 重新启动Nginx和uWSGI
./nginx
uwsgi3 --ini /root/project/learning_log/uwsgi.ini

现在再访问127.0.0.1应该就能正常联动了。

额外排查点(如果还是不行的话)

  • 检查8000端口是否被其他进程占用:netstat -tulpn | grep 8000,要是被占用就换个端口。
  • 单独测试uWSGI是否能正常运行:用uwsgi3 --http 127.0.0.1:8001 --module learning_log.wsgi启动,访问127.0.0.1:8001看是否能正常返回内容,排除WSGI模块本身的问题。
  • 如果用unix socket,要确保Nginx运行用户(比如www-data)对socket文件所在目录有读写权限,可以把Nginx用户加入uWSGI运行用户的组,或者设置socket权限为666(不推荐,但测试可用)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:26:40