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

DigitalOcean部署MERN应用时Nginx报111连接拒绝及Postman404问题求助

问题排查与解决步骤

两个问题高度关联,按以下顺序排查即可:

步骤1:确认后端Express服务正常运行

这是*connect() failed (111: connection refused)*报错的最常见原因:

  • 登录Droplet后执行 ps aux | grep node 查看是否有对应Node进程在运行
  • 若无进程,先检查后端启动日志,确认无MongoDB连接报错等启动失败问题,推荐用pm2托管后端进程,避免ssh断开后服务停止:
    # 安装pm2
    npm install pm2 -g
    # 进入后端项目目录后启动服务
    pm2 start server.js
    # 设为开机自启
    pm2 save && pm2 startup
    
  • 本地测试后端是否正常响应:在Droplet内执行 curl http://127.0.0.1:5000/api/messages,如果能正常返回数据说明服务本身无问题。

步骤2:修正Nginx配置错误

现有Nginx配置存在两处明显错误:

  1. proxy_pass路径重写错误:当前配置里location /api/ { proxy_pass http://localhost:5000/; }末尾的斜杠会把请求路径中的/api前缀切掉,例如前端请求/api/messages会被代理到后端的/messages,和你后端定义的/api/messages路由不匹配,直接导致404。
  2. 首行root路径拼写错误,缺少开头的/。

修正后的完整配置如下:

server {
    # 修正路径拼写错误
    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;
    server_name example.com www.example.com;

    location /api/ {
        # 去掉末尾斜杠,保留/api前缀传递给后端
        # 若仍报connection refused,可把localhost改为127.0.0.1避免ipv6解析问题
        proxy_pass http://localhost:5000;
        # 补充代理头,避免后续跨域、IP识别问题
        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;
    }

    location / {
        root /home/${my_non_root_user}/frontend/deploy;
        try_files $uri /index.html;
    }

    listen [::]:443 ssl ipv6only=on; #managed by Certbot
    listen 443 ssl; #managed by Certbot
    ssl_certificate /etc/letsencrypt/live/${example.com}/fullchain.pem; #managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/${example.com}/privkey.pem; #managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; #managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; #managed by Certbot
}

server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } #managed by Certbot

    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } #managed by Certbot

    listen 80 default_server;
    listen [::]:80 default_server;

    server_name example.com www.example.com;
    return 404; #managed by Certbot
}

修改完成后执行以下命令测试配置合法性并重启Nginx:

nginx -t
systemctl restart nginx

步骤3:修正Postman请求规则

当前Postman直接请求公网IP的/messages返回404的原因:

  • 你的Nginx配置仅绑定了example.com和www.example.com两个域名,公网IP访问不会匹配到该配置,会走默认的80端口404规则
  • 所有后端请求都需要加/api前缀
    正确请求地址为 https://example.com/api/messages,直接用绑定的域名发起请求即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 01:00:04