October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

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

A practical, evidence-led workflow for fixing Nginx 502 errors in front of Node.js, from log diagnosis and port checks to proxy_pass paths, timeouts, keepalive, testing, and reloads.
Length9 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A 502 Bad Gateway from Nginx means Nginx could not obtain a valid response from the Node.js upstream it is proxying to. Start with the error log, then verify that the Node process is running, listening on the port in proxy_pass, reachable on the expected address, and speaking the protocol Nginx expects. Only after those checks should you change URI handling, timeouts, or keepalive settings.

What an Nginx 502 means for a Node.js application

In a typical deployment, a browser connects to Nginx, and Nginx forwards the request to a Node.js server such as an Express, Fastify, or native HTTP application. The public HTTPS connection may terminate at Nginx; the connection from Nginx to Node is a separate upstream connection.

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.

A 502 is therefore usually not a browser problem and not proof that the route itself is broken. It means the proxy could not complete a valid exchange with Node. The failure can happen because the process is stopped, the port is wrong, the service is bound to an unreachable interface, the upstream scheme is wrong, the application takes too long to answer, or the proxy configuration sends an unexpected path.

Use the exact error text to choose the next check. A connection refusal points toward a process, port, or bind-address problem. An upstream timeout points toward an application that did not answer within the configured wait period. URI mistakes more commonly result in a 404, but they still need correction when Nginx rewrites the path before forwarding it.

1. Read the Nginx error log first

The error log is the quickest way to separate these cases. On many Linux distributions it is located at /var/log/nginx/error.log. Your distribution may use a different path or a systemd journal, so check the active Nginx configuration if that file is absent.

Watch the log while reproducing the error

sudo tail -f /var/log/nginx/error.log

In another terminal, request the failing URL. A single fresh log entry is more useful than a large historical dump. If the site has multiple virtual hosts or upstreams, include the timestamp and host name when matching an entry to your request.

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

Interpret the common failure families

Log indication What it usually means First check
Connection refused No process accepted the connection at the configured address and port, or a firewall or socket policy rejected it. Confirm the Node service is running and listening on the exact port in proxy_pass.
Upstream timed out Node did not return a response before the proxy timeout elapsed. Check application latency and raise the timeout only for the affected route when the log justifies it.
Invalid or unexpected upstream response Nginx reached the upstream but could not parse a valid HTTP response. Check that the upstream speaks HTTP on the configured scheme and that the application is not emitting malformed headers or closing early.

The wording varies by Nginx version and packaging. Treat the table as a diagnostic direction, then confirm the exact message in your installed log.

2. Confirm that the Node.js process is alive

Before changing Nginx, establish whether the application is actually running. A process manager such as systemd or PM2 may restart a crashing service, so inspect both its current status and recent logs.

systemd-managed service

sudo systemctl status my-node-app
sudo journalctl -u my-node-app --since '15 minutes ago'

Replace my-node-app with the unit name used on your server. Look for startup exceptions, missing environment variables, database connection failures, port-in-use errors, and repeated restart attempts. A service that is “active” but constantly restarting is not healthy enough for Nginx to proxy reliably.

PM2-managed application

pm2 status
pm2 logs --lines 100

Check the process name, restart count, and listening configuration. If PM2 starts a different entry point or environment than your manual shell command, it may be listening on a different port.

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.

Run the app locally without Nginx

When safe, query the upstream directly from the server. This distinguishes an application failure from a proxy failure:

curl -i http://127.0.0.1:3000/

A valid HTTP status, headers, and body show that something is answering on port 3000. A refusal means Nginx cannot succeed until the application or its address is corrected. If the request hangs, investigate the Node process and its dependencies before increasing any proxy timeout.

3. Verify the listening port and bind address

The port in Nginx must exactly match the socket opened by Node. Check listening sockets with:

sudo ss -tlnp | grep 3000

Change 3000 to the port your application is supposed to use. The output should identify a listening Node process. If there is no result, inspect the application’s configuration and startup logs rather than editing Nginx blindly.

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

Also verify the bind address. An application bound only to an interface Nginx cannot reach will produce the same practical result as a stopped service. For a same-host setup, binding to 127.0.0.1 is commonly appropriate when Nginx is also on that host. If Nginx proxies to another machine or container, Node must bind to an address reachable from that network, and the upstream address must point to that reachable interface.

Keep one source of truth for the port. Environment variables, a systemd unit, a container definition, and the Nginx file can otherwise drift apart. After changing the application port, restart the Node service and update Nginx to the same value.

4. Use a correct proxy_pass configuration

For a Node application listening on plain HTTP at 127.0.0.1:3000, a basic same-host location can look like this:

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 scheme is significant. Use http:// when Node serves ordinary HTTP. Public HTTPS termination at Nginx does not automatically mean the upstream connection must use HTTPS. Configure https:// only when the Node server itself is listening for TLS and has the required certificates and protocol settings. Sending an HTTPS request to a plain-HTTP Node listener can result in a 502 because the upstream exchange is not valid.

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

Check the address, port, and virtual host together

  • Confirm that the active server block is the one handling the failing hostname.
  • Confirm that proxy_pass uses the same host or IP that succeeded with your direct curl test.
  • Confirm that no included configuration overrides the location or defines a second upstream with the same name.
  • Check whether a container or separate host requires a service name or private IP instead of 127.0.0.1.

5. Understand how the proxy_pass URI changes the request path

Nginx treats a proxy_pass with and without a URI part differently. Without a URI, Nginx forwards the request URI as the client sent it. With a URI, Nginx replaces the portion matched by the location with that URI.

No URI part

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

A request for /api/users is forwarded with that request path. This is useful when Node’s router expects the /api prefix.

URI part with a trailing slash

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

Here the matched /api/ prefix is replaced by /, so the application receives /users. A missing or added trailing slash can therefore change which route Node sees. Such a mismatch usually causes a 404 rather than a 502, but it can trigger application behavior that appears to be a proxy failure. Test the intended path directly with curl and make the location and backend router agree.

6. Check the request headers passed to Node

At minimum, pass the original host and client address when the application uses host-based routing, absolute URLs, audit logs, or rate limiting:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;

Do not add arbitrary headers as a first response to a 502. Headers generally affect application behavior after a connection is established; they do not repair a stopped process or a wrong port. Add forwarding headers only when the application needs them and document their meaning.

7. Raise timeouts only when the log shows an upstream timeout

If the error log says upstream timed out, determine why the request is slow before changing configuration. Check database calls, external APIs, CPU saturation, event-loop blocking, large uploads, and synchronous work in the Node handler. A timeout setting can prevent a false failure for a legitimately long operation, but it cannot make a slow or dead application healthy.

Many guides describe a 60-second default for proxy_read_timeout; that value was not verified against every current Nginx build. Treat it as a guide-reported reference, not a universal promise. Set a longer value on the specific route that needs it:

location /reports/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_read_timeout 120s;
}

Keep the scope narrow. A global, very long timeout can leave workers occupied by hung requests and make an outage harder to recover from. Prefer asynchronous jobs and polling for operations that routinely exceed normal request durations.

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

8. Configure keepalive only when connection churn is the problem

Repeated connection setup can become expensive under load, but keepalive is not a general 502 cure. First establish from logs, connection metrics, or load symptoms that Nginx and Node are repeatedly opening and closing upstream connections.

The documented pattern for upstream HTTP/1.1 keepalive is:

proxy_http_version 1.1;
proxy_set_header Connection '';

The empty Connection header prevents Nginx from forwarding a hop-by-hop close directive to the upstream. Keepalive settings interact with upstream timeouts, worker limits, and the Node server’s own connection policy, so change one setting at a time and observe the result.

Nginx announced that upstream keepalive became the default in version 1.29.7, with HTTP/1.1 used by default for HTTP upstreams. Confirm that change in the release notes for the exact version installed on your server before relying on it; older versions require the explicit directives above. The upstream module also limits idle keepalive connections per worker, and a commonly reported summary gives a cap of 32, but verify the installed reference before tuning around that figure.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

9. Test and reload safely

Never reload an untested configuration. Run:

sudo nginx -t

Continue only when Nginx reports that the syntax test is successful. Then apply the change without a full restart:

sudo systemctl reload nginx

A reload makes the new configuration active while allowing existing workers to finish their current work. If the test fails, use the file name and line number in the output to fix the syntax or include-path error. If the reload succeeds but 502 responses continue, return to the fresh error-log entry; a successful reload proves syntax, not upstream health.

Verify from both sides

  1. Request the Node endpoint directly from the Nginx host with curl -i.
  2. Request the public URL through Nginx and compare status, headers, and response time.
  3. Watch the Nginx error log and Node application log during the same request.
  4. Repeat with the exact path that previously failed, including any /api prefix.

10. A focused recovery checklist

  • Capture the exact Nginx error-log line and timestamp.
  • Check the Node service status and recent application logs.
  • Confirm a listener exists on the configured port with ss -tlnp.
  • Call the upstream directly from the Nginx host.
  • Match the proxy_pass scheme, address, and port to that successful direct call.
  • Confirm the bind address is reachable from Nginx.
  • Review trailing-slash and prefix behavior when the request path is rewritten.
  • Increase proxy_read_timeout only for a route whose log shows an upstream timeout.
  • Use HTTP/1.1 and an empty Connection header only when connection reuse is relevant.
  • Run nginx -t, reload, and retest while watching both logs.

Common mistakes that prolong a 502 outage

Changing Nginx before checking Node

Adding headers, disabling buffering, or increasing every timeout cannot help when the process is stopped or listening elsewhere. Prove that the direct upstream request works first.

Using the public HTTPS scheme for every hop

Nginx’s public listener and its upstream connection are independent. Match the upstream scheme to what Node actually serves.

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

Applying a global timeout increase

A long global timeout can consume proxy capacity when an application is hung. Scope the setting to the route and address the slow dependency in Node.

Assuming a path mismatch is a network failure

Trailing-slash behavior can send a different URI to Node. Compare the path received by the application before treating a route-level 404 or redirect as an upstream outage.

Skipping the configuration test

Editing a live file without nginx -t can leave the old configuration active or prevent a reload altogether. Always read the test output and confirm the reload completed.

When the 502 persists after these checks

If direct requests to Node fail, continue on the application side: inspect startup exceptions, dependency health, resource exhaustion, and process-manager restarts. If direct requests succeed but the public request fails, compare the active Nginx server block, upstream address, URI transformation, and protocol. For containerized deployments, verify network membership and service-name resolution. For multi-host deployments, verify firewall rules and that the private address is reachable from the Nginx machine.

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

Keep the error-log line, the exact configuration tested, the direct upstream response, and the corresponding Node log entry together. That evidence identifies whether the remaining fault is process availability, connectivity, protocol negotiation, request rewriting, or application latency, and prevents repeated changes that do not address the actual failure.

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 quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.