I'm serving both React app and NodeJS API with Nginx configuration (from Nginx sites-available
folder):
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;
}
}
If I start the NodeJS API on the server with npm start
- everything works. If I run the API as a process with PM2 - I get 502 Bad gateway by calling any API endpoint.
EDIT: PM2 doesn't serve app at expected port (3000). Found out by turning it off.
So the issue was not serving the app at expected port (3000).
The problem was in my server.js
file which I ran by pm2 start server.js
. I saw many suggestions online to start NodeJS app with pm2 start./bin/www
command. You can do this if your Express NodeJS project is initialized by Express application generator .
My project wasn't initialized by Express generator, so I created a dummy project to see content of ./bin/www
file.
> mkdir my-app
> cd my-app
> npx express-generator
Then I copied content of www
file which is located in bin
directory to my server.js
file. Only change was in line 7:
var app = require('../app');
I changed it to
var app = require('./app');
Because both server.js
and app.js
files are located in my project root.
I went through the same issues while setting up my staging server. Posted a similar question
Few things that worked for me:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.