繁体   English   中英

PM2, 502 Bad gateway, Nginx 同时服务于 React 应用程序和 NodeJS API

[英]PM2, 502 Bad gateway, Nginx serving both React app and NodeJS API

我正在为 React 应用程序和 NodeJS API 提供 Nginx 配置(来自 Nginx sites-available文件夹):

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

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name my-site-name.com www.my-site-name.com;

    location /api/ {
        proxy_pass http://localhost:3000;

        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
    }

    location / {
        root /var/www/html/;
        try_files $uri /index.html;
    }
}

如果我在 npm 启动的服务器上npm start - 一切正常。 如果我使用 PM2 将 API 作为进程运行 - 我通过调用任何 API 端点得到 502 Bad gateway。

编辑:PM2 不在预期端口(3000)提供应用程序。 关掉就知道了。

所以问题不是在预期的端口(3000)上为应用程序提供服务。

问题出在我由pm2 start server.js运行的server.js文件中。 我在网上看到很多建议使用pm2 start./bin/www命令启动 NodeJS 应用程序。 如果您的 Express NodeJS 项目由Express 应用程序生成器初始化,您可以执行此操作。

我的项目没有被 Express 生成器初始化,所以我创建了一个虚拟项目来查看./bin/www文件的内容。

> mkdir my-app
> cd my-app
> npx express-generator

然后我将位于bin目录中的www文件的内容复制到我的server.js文件中。 唯一的变化是在第 7 行:

var app = require('../app');

我把它改成

var app = require('./app');

因为server.jsapp.js文件都位于我的项目根目录中。

我在设置登台服务器时遇到了同样的问题。 发布了一个类似的问题

对我有用的几件事:

  • 在服务器端代码中错过它们的任何地方都使用 try/catch 循环
  • 确保正确读取所有环境变量
  • 检查 pm2 日志中是否存在节点错误
  • 检查 nginx 日志中的配置错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM