Troubleshooting React/Express on Nginx/Ubuntu: Fixing 521 Bad Gateway Error

Abstract: Resolve Nginx 521 Bad Gateway errors by verifying Express.js is running, listening on the correct port and interface, and accessible via local curl tests.

Created: 2026-09-15 by
The 521 Bad Gateway error in Nginx indicates that the reverse proxy cannot establish a connection to the upstream backend, typically your Express.js server. This is rarely an Nginx configuration error but rather a failure of the Node.js process to listen on the expected port or IP address. Resolving this requires verifying that the backend service is running, accessible locally, and correctly bound to the network interface specified in your Nginx configuration.

Understanding the 521 Error Code

HTTP status code 521 is specific to Cloudflare’s infrastructure but is widely adopted by other reverse proxies like Nginx to indicate "Web Server Is Down." When Nginx receives this response, it means it successfully contacted the target server (the Express app), but the TCP handshake failed immediately. The most common causes are that the Node.js process has crashed, is not listening on the correct port, or is bound only to localhost while Nginx expects a broader network interface.

Before diving into complex networking diagnostics, you must confirm the health of the application itself. A static React build served by Nginx does not trigger 521 errors; those are strictly associated with proxied API requests or server-side rendering handled by Express. If your React frontend loads but API calls fail, the issue lies entirely within the Express backend connectivity.

Verifying Backend Service Status

The first step is to ensure that your Express application is actually running and responsive. Use system utilities to check the process state and network bindings. Run the following command to list active processes containing node:

ps aux | grep node

If the process is missing, start it using your preferred process manager, such as PM2 or systemd. For example, if using PM2:

pm2 start server.js

Once the process is running, verify which ports it is listening on. Use netstat or ss to inspect the socket status:

sudo ss -tlnp | grep :3000

Look at the local address column. If you see 127.0.0.1:3000, the server is only accepting connections from the local machine. While this works for Nginx running on the same server, it can sometimes cause issues depending on how Nginx resolves the upstream. Ideally, you want to see 0.0.0.0:3000 or *:3000, which binds to all available network interfaces. If the output shows LISTEN next to the port, the service is ready to accept connections.

Testing Connectivity Locally

To isolate whether the issue is with Nginx or the backend, bypass the reverse proxy entirely. Use curl to request data directly from the Express server:

curl http://127.0.0.1:3000/api/health

If this returns a valid JSON response or HTML content, your Express app is functioning correctly. If it hangs or returns a connection refused error, the problem is internal to the Node.js application, not Nginx. In this case, check your Express code to ensure you are calling app.listen(port, '0.0.0.0') rather than just app.listen(port), which defaults to localhost.

If the direct curl test fails, review your Express logs for startup errors, database connection failures, or unhandled exceptions that might cause the process to exit silently. You can also try binding to a different port temporarily to rule out port conflicts with other services on Ubuntu.

Reviewing Nginx Configuration

If the backend is confirmed working via direct access, examine your Nginx site configuration file, typically located in /etc/nginx/sites-available/. Look for the upstream block or the proxy_pass directive within your server block.

server {
    location /api/ {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}

Ensure that the IP address and port in proxy_pass exactly match what ss reported earlier. A common mistake is specifying localhost instead of 127.0.0.1, which can resolve differently depending on IPv6 settings. Also, verify that the Nginx user (www-data) has permission to connect to the port, although this usually results in a 502 error rather than 521.

After making changes, test the configuration syntax before reloading:

sudo nginx -t

If the test passes, reload Nginx:

sudo systemctl reload nginx

For more insights on managing Ubuntu server networks during such deployments, see How do Ubuntu-server network interfaces work?.

Checking Firewall and Security Groups

Although 521 implies the server is reachable but unresponsive, firewall misconfigurations can sometimes interfere with loopback traffic or specific IP bindings. On Ubuntu, check ufw status:

sudo ufw status

Ensure that port 3000 (or your chosen backend port) is allowed if external testing is required. However, for local Nginx-to-Express communication, firewall rules generally do not apply to loopback interfaces. If you are using Cloudflare, ensure that the origin pull certificate and SSL settings are configured correctly, as mismatched TLS versions can also trigger gateway errors.

Additionally, if you recently moved servers or changed network environments, DNS resolution issues might affect how Nginx resolves upstream names. Check Fixing DNS Issues When Moving Headless Ubuntu 22.04.5 LTS Server to a New Network if you suspect hostname resolution problems.

Frequently Asked Questions

Why does my React app load but API calls return 521?

This confirms that Nginx is successfully serving static files but failing when trying to proxy dynamic requests to the Express backend. The issue is isolated to the Node.js process or its network binding, not the Nginx static file serving logic.

Can IPv6 cause a 521 error in Nginx?

Yes, if your Express app binds only to IPv4 (127.0.0.1) but Nginx attempts to connect via IPv6 ([::1]), the connection will be refused. Ensure both services use compatible IP versions or explicitly set the upstream to 127.0.0.1 in Nginx.

How do I check if my Node.js process crashed?

Use pm2 status if you manage processes with PM2, or systemctl status your-service-name for systemd units. Check logs with journalctl -u your-service-name -e to identify fatal errors that caused the crash.

What is the difference between 502 and 521 errors?

A 502 Bad Gateway means Nginx could not get a valid response from the upstream, often due to malformed headers or timeouts. A 521 specifically means the TCP connection was refused immediately upon attempt, indicating the backend service is not listening on that port.

Should I bind Express to 0.0.0.0 or localhost?

Binding to 0.0.0.0 is safer for development and ensures accessibility from any interface. Binding to localhost restricts access to the local machine, which is fine if Nginx runs on the same host but can cause confusion if you switch to Docker or remote debugging.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More