Error 502: Nginx's connection to the Express server is experiencing issues

Greetings! I recently migrated my website from AWS with PM2 to a nginx server on Digital Ocean. However, I am encountering a 502 error, indicating that something is misconfigured. Originally, the client was served successfully, but after switching to having the server handle it as well, the 502 errors started occurring.

Both the client and server folders are located in the same parent directory. Here is the current configuration in the var/nginx/sites-available/default file:

# Main Content Delivery Block (SSL)

server {
    listen              443 ssl;
    listen              [::]:443 ssl;
    server_name         quakeviz.app;
    ssl                 on;
    ssl_certificate     /etc/ssl/certs/mpaccione_ssl.crt;
    ssl_certificate_key /etc/ssl/private/mpaccione_ssl.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    add_header          Content-Security-Policy upgrade-insecure-requests;

    location / {
        root        /var/www/html/usgs_viz/server;
        proxy_pass  https://quakeviz.app:8080/;
        proxy_ssl_session_reuse on;
        #try_files  $uri $uri/ /;
    }

    #location /bufferLength {
    #   root                    /var/www/html/usgs_viz/server;
    #   proxy_pass              https://quakeviz.app:8080/;
    #    proxy_ssl_session_reuse on;
    #}

    #location /quakeData {
    #   root                    /var/www/html/usgs_viz/server;
    #   proxy_pass              https://quakeviz.app:8080/;
    #   proxy_ssl_session_reuse on;
    #}
}

# Redirect 

#server {
#   listen 80 default_server;
#   listen [::]:80 default_server;
#   listen 443 ssl;
#   listen [::]:443 ssl;
#
#   return 301 https://quakeviz.app$request_uri;
#}

Furthermore, I have included the index.js code snippet from the server folder below. Following an update, I now encounter a 502 error on both the client and API sections of the website:

// Modules
const cors = require('cors'),
  express = require('express'),
  expressStaticGzip = require('express-static-gzip'),
  fs = require('fs'),
  path = require('path'),
  app = express(),
  // Globals
  getDirectories = (source) => {
    return fs
      .readdirSync(source, { withFileTypes: true })
      .filter((dir) => dir.isDirectory())
      .map((dir) => dir.name)
  }

// CORS for Local Testing

app.use(cors())

// Compression

app.use(
  '/',
  expressStaticGzip(path.join(__dirname, '../client/build'), {
    enableBrotli: true,
    orderPreference: ['br', 'gz'],
  })
)

// Routes

app.get('/', function (req, res) {
  res.sendFile(path.join(__dirname, '../client/build', 'index.html'))
})

app.get('/.well-known(/*)?', function (req, res) {
  res.sendFile(path.join(__dirname, '../.well-known', 'assetlinks.json'))
})

app.get('/privacy-policy', function (req, res) {
  res.sendFile(path.join(__dirname, '../privacy_policy.html'))
})

// API - Please note these server-side routes

...

// Listen

app.listen(8080, () => console.log('API listening on 8080'))

Answer №1

It's puzzling why you're attempting to proxy each route of your service instead of letting your app handle the request routing itself.

For example:

 location / {
    root                    /var/www/html/usgs_viz/server;
    proxy_pass              https://quakeviz.app:8080/;
    proxy_ssl_session_reuse on;
}

Another observation is the use of HTTPS in the proxy_pass directive, which may not work as intended. Consider replacing it with HTTP instead.

Answer №2

I made some updates to my setup, including running the server with PM2.

As I dive deeper into the world of fullstack sysadmin, I realized that I needed to utilize PM2 in addition to routing through Nginx. Previously, I mistakenly thought Nginx would handle everything if pointed to it directly. Lesson learned! The nginx configuration below is now more optimized for my needs:

# Main Content Delivery Block (SSL)

server {
    listen              443 ssl;
    server_name         quakeviz.app;
    ssl                 on;
    ssl_certificate     /etc/ssl/certs/mpaccione_ssl.crt;
    ssl_certificate_key /etc/ssl/private/mpaccione_ssl.key;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;
    add_header          Content-Security-Policy upgrade-insecure-requests;

    location / {
        root                /var/www/html/usgs_viz/server;
        proxy_pass          http://localhost:8080;
        proxy_http_version  1.1;
        proxy_set_header    Upgrade $http_upgrade;
        proxy_set_header    Connection 'upgrade';
        proxy_set_header    Host $host;
        proxy_cache_bypass  $http_upgrade;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a custom regular expression in ExpressJS: matching a parameter to all routes except for one

My current route is set up to catch the code param in the following way: app.get('/:code([a-zA-Z]{3})', codeHandler); This setup successfully matches all three-letter codes, but now I want to modify it to exclude one specific code. For example, ...

Browsing data privacy is crucial, which is why I have decided to operate both servers on the same port to ensure that cookies are

In my project, the front end is built with Next.js and the backend uses Express and Node.js. These projects are currently running on different ports - the frontend on port 3000 and the backend on port 8080. While everything works fine locally and cookies a ...

Pictures fail to appear in https but are visible when using http

After successfully building my first personal website using the MERN stack, I encountered an issue when trying to deploy it on AWS Lightsail. While everything seemed to be working fine in HTTPS mode, the images were not displaying properly. When clicking o ...

Using Node.js and Express to import a simple JavaScript file as a router

Can anyone help me understand how to import the user.json json file into my user.js? I want the json file to be displayed when typing /user but I'm struggling with the new version of Node. index.js import express from 'express'; import body ...

Exploring dependencies in Node.js with depcheck to uncover instances of require('x') where 'x' is not listed in the package.json file

Recently, I came across a library called depcheck: https://www.npmjs.com/package/depcheck Initially, I assumed that it would solve my problem of finding modules used in the code but not declared in package.json. However, to my disappointment, it only loo ...

Troubleshooting problems with querying in mongoose and express: A comprehensive guide

As someone who is still relatively new to dynamic routing, I am struggling with implementing it correctly. My goal is to create a function that retrieves the user's purchases from the database and exports it as a CSV file. Everything was working fine ...

The getInitialProps method does not have access to the Passport user object in the request when the server is running on a different port

I currently have my express server running on a separate port from my client-side nextjs project. Typically, when the server is on the same port as the client, you can use getRequestHandler with next to pass the user object that can be accessed in the cli ...

Attempting to transfer user information to MongoDB using AngularJS and Node.js

Greetings everyone! I am currently working on a template and trying to develop a backend for it, starting with the registration form. Despite having some kind of connection between my mongodb and my app, data is not being sent to the database. Here is the ...

Performing a MySql query to retrieve data from two tables often leads to a high number of redundant entries

I'm currently utilizing the latest version 8.* of MySQL from Oracle. In my setup, I am using node.js in conjunction with express and have multiple tables that share the same structure involving an auto_increment id and some columns. For the index page ...

Adjust image size using Node.js and ImageMagick

How can I resize images before sending them to users in Node.js using Express? im = require("imagemagick") app.get('/image/:dossier/:id/:taille', function (req, res) { var image = __dirname + '/public/img/bibliotheque/'+req.params ...

Ways to filter out specific fields when returning query results using Mongoose

I was wondering about the code snippet below: Post.create(req.body) .then(post => res.status(201).json(post)) .catch(err => res.status(500).json(err)) While this code works perfectly, I am curious about excluding a specific field, such as the __v fi ...

Saving numerous files with Promises

There is a Node URL (created using Express) that enables users to download static images of addresses. The calling application sends a request to the /download URL with multiple addresses in JSON format. The download service then calls Google Maps to save ...

Searching for and retrieving only the objects in an array that meet a specified condition can be achieved using the FindOne function

Currently, I have a scenario where I need to extract specific objects from the array user_surveys, but only those with a survey_delete_flag value of 0. { "_id":"5d38395531335242147f9341", "user_status":"Active", "user_surveys":[ ...

Encountering HTTP 502 Error While Navigating Rendr Examples Through Clicking Links

I successfully set up and launched Rendr's example applications on Ubuntu 13.10 using Node v0.8.6. However, I encountered an issue where clicking on the Repos or Users links resulted in an HTTP 502 - Bad Gateway error. Interestingly, upon refreshing t ...

Using Promise to manipulate objects and arrays returned from functions

https://i.stack.imgur.com/jvFzC.png router.get('/', function (req, res, next) { var size = req.params.size ? parseInt(req.params.size) : 20; var page = req.params.page ? req.params.page>0 ? (size&(parseInt(req.params.page)-1)) : ...

Issue encountered when attempting to send FormData from Next.js API to Express.js backend resulting in Error 405: Bad Request

SOLVED / SEE MY OWN ANSWER FOR DETAILS Encountering a perplexing error that has left me stuck. I am currently facing an issue where I am trying to send an audio recording captured by the user in my Next.js Frontend to my Next.js API, which appears to be f ...

Differences between NextJS default server-side rendering and implementing a custom server

What are the benefits of using Express (or another server) when implementing SSR with Next.js instead of simply using the built-in next start command for initialization? ...

Is the MVC pattern adhered to by ExpressJS?

Currently, I am diving into the world of creating an MVC Website With ExpressJS using resources from I'm curious to know if ExpressJS strictly adheres to the MVC pattern, or if it follows a different approach like Flask which focuses more on the "C" ...

I am wondering if it is feasible for a POST route to invoke another POST route and retrieve the response ('res') from the second POST in Express using Node.js

Currently, I have a POST route that triggers a function: router.route('/generateSeed').post(function(req,res){ generate_seed(res) }); UPDATE: Here is the genrate_seed() function function generate_seed(res) { var new_seed = lightwallet. ...

Secure your Express.js session cookies for enhanced protection

Struggling to figure out how to set a secure cookie in the expressjs framework. Any suggestions on where I can find an option for this? ...