October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk11 min

How to Fix an Nginx 502 Bad Gateway Error With a Node.js App

A practical, evidence-led guide to fixing Nginx 502 Bad Gateway errors in front of Node.js, from error-log diagnosis through proxy configuration and reload verification.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

An Nginx 502 Bad Gateway in front of Node.js usually means Nginx could not obtain a valid response from the upstream Node process. Check the error log first, then verify that the process is running, listening on the port in proxy_pass, reachable on the expected address, and speaking the expected protocol. Only after those checks should you change URI handling, timeouts, or keepalive settings.

What a 502 means in an Nginx-to-Node.js setup

Nginx is acting as a reverse proxy. The browser connects to Nginx, and Nginx opens a second connection to your Node.js application. A 502 means the proxy could not use the upstream response. That can happen because the application is stopped, the port is wrong, the process is bound to an unreachable interface, the upstream protocol is wrong, or the application does not answer before the configured proxy timeout.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This is different from an application-generated error page. If Node.js deliberately returns an HTTP 500, Nginx can normally pass that response through. A 502 is generally evidence of a failed or invalid connection between Nginx and the upstream.

Use this order to avoid random configuration changes:

  1. Read the Nginx error log at the time of a failed request.
  2. Confirm that the Node.js process is alive and listening.
  3. Make the proxy_pass scheme, address, and port match the Node server.
  4. Check URI rewriting if the request reaches the wrong application path.
  5. Increase a route-specific timeout only when the log shows an upstream timeout.
  6. Configure keepalive only when connection churn or sustained load justifies it.
  7. Test and reload Nginx.

Start with the Nginx error log

The access log tells you that a request returned 502; the error log usually explains why. On many Linux distributions, the file is /var/log/nginx/error.log. If your installation uses a different path, check the error_log directive in the active configuration.

Inspect entries written at the same moment as the failed request. The wording varies by Nginx version, but these two patterns provide the first branch in the diagnosis:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Log indication Likely direction First checks
connect() failed ... connection refused Nothing accepted the connection at the configured upstream address and port. Check whether Node is running, whether it listens on the expected port, and whether proxy_pass points to that port.
upstream timed out Nginx connected or attempted to connect, but did not receive a usable response within the proxy timeout. Check Node-side logs and request duration, then adjust the affected route’s timeout only if the workload legitimately needs more time.

These interpretations are practical starting points rather than a substitute for the exact log line from your installed version. A connection error can also reflect a wrong address or a socket that is reachable from another network namespace but not from Nginx. A timeout can indicate a blocked event loop, a slow dependency, or an overloaded process rather than a value that should simply be increased.

Verify that Node.js is running and listening

Check the process manager

Find how the application is supervised. With systemd, inspect the service status and recent journal entries. With PM2 or another process manager, inspect the process list and restart history. A process can appear configured to start automatically while repeatedly crashing during boot, so look for an active listener rather than relying only on a service definition.

  • Confirm the process is currently alive.
  • Read its startup and crash output for missing environment variables, binding errors, or uncaught exceptions.
  • Check whether a recent deployment changed the port, host binding, or start command.

Check the listening socket

On the server, run a socket check such as:

ss -tlnp | grep 3000

Replace 3000 with the port your application is intended to use. The output should show a listening TCP socket and, where permitted, the owning process. If there is no listener, fix the Node process before editing Nginx. If the listener is on another port, either correct the application configuration or make proxy_pass match it.

Check the bind address

Node must bind to an address Nginx can reach. A listener bound only to an inaccessible interface will produce the same practical symptom as a stopped application. For a same-host deployment, binding to loopback and proxying to the same loopback address is a common arrangement. If Nginx runs in a container, virtual machine, or separate host, 127.0.0.1 refers to Nginx’s own environment, not automatically to the machine running Node.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test the upstream directly from the environment where Nginx runs. For a local HTTP listener, a request such as curl -i http://127.0.0.1:3000/ should produce an HTTP response from Node. A refusal, timeout, or inability to resolve the address narrows the problem before Nginx is involved.

Make proxy_pass match the Node server

Use HTTP for a plain-HTTP Node upstream

TLS for the public site is commonly terminated at Nginx. That does not make the private hop to Node HTTPS. If Node is serving ordinary HTTP, use an http:// upstream in proxy_pass. Using https:// against a plain-HTTP Node listener can prevent a valid upstream response. Use HTTPS only when Node itself is configured to speak TLS and has the required certificates.

Use the correct address and port

A minimal same-host location block is:

location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_read_timeout 60s;
}

The port in this example is not universal; it must be the port on which your Node process actually listens. If your application listens on another port, change both the application or proxy configuration so that there is one deliberate, matching value. Do not solve a port mismatch by adding unrelated timeout or keepalive directives.

Check the active server block

Nginx can have several configuration files and server blocks. You may edit one file while a different block handles the hostname. Validate which block serves the requested domain, then inspect the effective configuration if your distribution provides a command or include layout for doing so. A correct location block in an unused file cannot change the response.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Understand the trailing-slash rule in proxy_pass

The URI portion of proxy_pass controls how Nginx constructs the path sent upstream. This affects routing and commonly explains an upstream 404, even though it is not usually the direct cause of a 502.

  • When proxy_pass has no URI part, Nginx passes the request URI as the client sent it.
  • When it includes a URI part, Nginx replaces the portion of the request that matched the location with that URI.

For example, these two blocks do not send the same path:

location /api/ {
    proxy_pass http://127.0.0.1:3000;
}

A request for /api/users is forwarded with the /api/users path.

location /api/ {
    proxy_pass http://127.0.0.1:3000/;
}

Here, the matching /api/ prefix is replaced by /, so the upstream receives /users. Choose the form that matches the routes implemented by your Node application. Treat the slash as an intentional routing decision, not as formatting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Forvencer Server Book, 2 Zipper Pocket, Server Books for Waitress
  • Upgraded Two Zipper Pockets: Forvencer server books feature two secure zipper pockets for better organization of coins, cash, and receipts, ensuring that everything you collect has a safe and secure place
  • Smart Storage & Quick Access: Designed with 8 multi-functional compartments, the right side includes a guest receipt pad, while the left has a money pocket, ticket pocket, and credit card slot. Two small clear pockets store bills, receipts, and other visible items. A stitched pen loop ensures you always have your favorite pen ready
  • High-quality & Easy to Clean: Crafted from high-quality PU leather with heavy-duty stitching, this server book is built to last. It resists tears, scratches, and its waterproof surface makes cleaning easy with just a damp cloth or a non-chlorine sanitizer
  • Perfect Fit for Your Apron: Measuring 5” x 8”, this compact organizer is slightly smaller than other models, making it ideal for bending or sitting while carrying in your server apron. It holds everything a waitress needs—a place for everything
  • What's Included: This server organizer comes with multiple open and zippered pockets to store money, receipts, tips, etc. Clear sleeves are perfect for keeping menus or special lists while serving. Available in a variety of colors, allowing you to express yourself even when in uniform

If the application logs show that the request reaches Node but the route is missing, inspect this rule before changing the upstream address. URI mismatches normally produce 404 or another application response rather than a 502, but they can obscure the original problem when several symptoms occur together.

Fix upstream timeouts without hiding slow code

When the error log says upstream timed out, identify which operation is slow. Check Node logs, database calls, external API requests, file operations, and event-loop blocking work. A higher proxy timeout is appropriate only when the route is expected to take that long and the application can handle concurrent requests safely.

Many configuration guides describe a 60-second default for proxy_read_timeout, but the exact default and effective value should be verified against the Nginx version and inherited configuration on your server. The example block uses proxy_read_timeout 60s; explicitly so its behavior is visible; it does not prove that every installation starts with that value.

Change the narrowest location

Put a longer timeout on the specific location that performs a legitimate long-running operation instead of raising it globally:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
location /reports/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_read_timeout 120s;
}

Use a value appropriate to the route’s documented behavior. A large global timeout can leave connections occupied while Node is unhealthy, increase resource pressure, and delay failure detection. If the operation should be asynchronous, a job queue and status endpoint are usually safer than holding a browser request open, but that is an application design change rather than an Nginx fix.

Distinguish connection timeout from read timeout

A failure while opening the upstream connection points back to the process, address, port, or network path. A read timeout means Nginx did not receive data in time after the request was sent. Do not treat every timeout as evidence that proxy_read_timeout must be increased; use the error-log wording and application timing to choose the setting.

Use keepalive deliberately under load

Repeatedly opening upstream connections can add overhead when many requests arrive. For upstream keepalive, the documented pattern uses HTTP/1.1 and an empty Connection header:

location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

The empty header prevents Nginx from sending a hop-by-hop Connection value that disables reuse. Keepalive is not a cure for a crashed process, a wrong port, or a protocol mismatch. Add it when logs, connection counts, or load behavior indicate connection churn, and then observe both Nginx and Node after the change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Account for your Nginx version

An Nginx blog announcement reports that upstream keepalive became the default in version 1.29.7, with HTTP/1.1 used by default for HTTP upstreams. That version-specific change should be checked against the release notes and reference documentation installed with your distribution. Before that change, explicitly setting proxy_http_version 1.1 and proxy_set_header Connection "" was the standard way to request this behavior.

Reference summaries also describe an idle keepalive limit of 32 connections per worker process. Because the exact limit and its version context must be verified against the live upstream-module documentation, do not design capacity plans around that number without checking your installation. Keepalive settings interact with worker counts, upstream timeouts, file-descriptor limits, and the Node server’s own connection policy.

Watch for header and timeout interactions

If clients or upstream logs show connections being closed unexpectedly, inspect the effective proxy_http_version and Connection directives in the location that handles the request. Keepalive changes how idle sockets are retained; it does not make an unresponsive upstream healthy. A timeout while proxying to another HTTP server can be related to keepalive behavior, so test changes under representative traffic rather than applying several directives at once.

Validate the configuration and reload safely

  1. Run sudo nginx -t. Do not reload if the syntax test fails.
  2. Read the error reported by the test and correct the referenced file, directive, or include.
  3. After a successful test, run sudo systemctl reload nginx.
  4. Reload, rather than fully restarting, when you only need Nginx to adopt configuration changes. A reload applies the new configuration while existing workers finish their current work.
  5. Send a new request and inspect both the access and error logs.

Keep the previous working configuration available until the new request succeeds. If the reload command reports success but the response is unchanged, confirm that the request is reaching the server block and host you edited.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Common 502 causes and the precise correction

Node stopped or repeatedly crashing

Start or repair the supervised service, then confirm a listening socket. Read the Node startup output; a successful process-manager command is not enough if the application exits immediately.

Wrong port

Compare the port in the Node configuration, the output of ss -tlnp, and the port in proxy_pass. Make them agree, then test the upstream directly.

Wrong bind address

Change the Node bind address or the Nginx upstream address so that the two processes can reach each other. Remember that loopback addresses are local to the network environment in which they are used.

HTTP/HTTPS mismatch

Use http:// for a plain-HTTP Node listener and https:// only for a Node listener configured for TLS. Public HTTPS at Nginx does not automatically require HTTPS on the private upstream hop.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Path rewritten unexpectedly

Compare the request path in Nginx and Node logs, then choose a proxy_pass with or without a URI part as required by the application routes. This usually resolves a 404 or route error rather than a transport 502.

Application response too slow

Find the slow dependency or blocked work first. Set a longer proxy_read_timeout only on the affected route when the delay is expected and safe.

Connection churn under load

Measure connection behavior and enable the HTTP/1.1 and empty-Connection-header pattern where appropriate. Verify the behavior for your Nginx version and monitor idle sockets and file descriptors.

A compact decision path

Use the first matching condition rather than changing every setting:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • The log says connection refused: check the process, listening port, bind address, and upstream scheme.
  • The log says upstream timed out: inspect Node latency and dependencies; then adjust the affected route’s read timeout if justified.
  • Node receives the request but returns a route error: inspect the proxy_pass URI and trailing slash.
  • Failures appear only during high concurrency: investigate connection reuse, worker and file-descriptor capacity, Node saturation, and upstream timeout interaction.
  • The configuration test fails: fix syntax or include errors before attempting another reload.

Prevent the next 502

  • Keep the Node listening port in one documented configuration source and make the Nginx upstream match it.
  • Record whether the private hop is HTTP or HTTPS; do not infer it from the public URL.
  • Monitor the Node process for crash loops, not just whether its service is enabled.
  • Keep Nginx error logs available with timestamps so a failed request can be correlated with an application event.
  • Use route-specific timeout values for known long operations instead of a large global value.
  • After Nginx or Node upgrades, verify changed defaults such as upstream HTTP version and keepalive behavior.
  • Test a direct upstream request from the same environment as Nginx before blaming the proxy.

Final verification checklist

  • The Node process is running and remains running after a request.
  • A socket check shows Node listening on the expected address and port.
  • The proxy_pass scheme matches the protocol Node actually serves.
  • The proxy_pass port matches the listening socket.
  • The location’s URI behavior matches the routes in the Node application.
  • The error log no longer reports connection refusal or an unjustified upstream timeout.
  • sudo nginx -t succeeds.
  • sudo systemctl reload nginx completes successfully.
  • A fresh request returns the expected application response.

The reliable fix is therefore diagnostic rather than cosmetic: identify the upstream failure in the error log, make the Node process reachable at the exact address and protocol configured in proxy_pass, correct path handling where necessary, and tune timeouts or keepalive only for evidence-backed behavior.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.