Nginx 反向代理:抛出 502 错误网关

问题描述 投票:0回答:3

我正在阅读本教程来了解反向代理 https://www.youtube.com/watch?v=ZmH1L1QeNHk&t=227s

我正在像这样运行 docker 镜像

sudo docker run -d --name nginx-base -p 80:80 nginx:latest

我能够编辑default.conf 这是文件

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

    location /test {
        proxy_pass http://localhost:8086/test;
    }

    location /home {
        proxy_pass http://localhost:3000;
    }

   location /home/auth {
        proxy_pass http://localhost:3000/auth;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}
    
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}
    
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}
     
    

当我访问 http://localhost/ 时,我会看到 Nginx 欢迎屏幕

但是当我尝试访问时 http://localhost/test 或 http://localhost/home

此外,我还可以访问

localhost:3000
localhost:8086/test

不确定为什么 nginx 会抛出 502,我是否错过了任何配置?

docker nginx reverse-proxy bad-gateway
3个回答
2
投票

错误网关 502 通常表示您的目标服务器没有响应。 我假设你的其他服务也是 Docker 容器?如果是这种情况,您可以尝试将 localhost 更改为其容器名称并使用 Docker-dns。但您需要将所有容器放在同一个网络中才能正常工作。

另一件事是要尝试颠倒路线顺序。如果我没记错的话,nginx 会采用第一个匹配的路由。在你的情况下 / 匹配所有其他路由,因此每个请求都会定向到你的 nginx。但你的 nginx 无法处理 /test 或 /home。

我希望这能帮助您找到问题所在。


0
投票

就我而言,这是防火墙问题。我禁用了防火墙,它起作用了。

我通过curl docker IP得到了线索,它正确输出了html主页。

sudo ip addr show docker0
4: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default
    link/ether 02:42:a9:60:8e:f4 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
       valid_lft forever preferred_lft forever

curl 172.17.0.1:5870

我让应用程序在端口 5870 上运行,在禁用防火墙之前:

curl 127.0.0.1:5870
curl: (56) Recv failure: Connection reset by peer

curl 0.0.0.0:5870
curl: (56) Recv failure: Connection reset by peer

之后:我得到了 HTML 页面输出。


0
投票

关于502 bad gateway,您还可以参考以下内容: https://www.httpstatuscodes.cc/statuscode/502-bad-gateway

© www.soinside.com 2019 - 2024. All rights reserved.