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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

A 502 Bad Gateway from nginx means the reverse proxy could not obtain a valid response from the Node.js upstream. In practice, the cause is usually a stopped Node process, a port or bind-address mismatch, an incorrect proxy_pass, a path rewrite that sends the wrong URI, or an upstream that exceeds its timeout.

Work from the inside out: read the nginx error log, prove that Node is listening where nginx expects, test that socket directly, correct the proxy block, change timeouts only when the log justifies it, and then validate and reload nginx. The procedure below covers same-host deployments and notes the version-dependent behavior that can affect keepalive connections.

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

What the 502 means in this setup

The request path is client → nginx → Node.js. Nginx accepts the client request, opens a connection to the address in proxy_pass, and waits for an HTTP response. A 502 is generated when that upstream exchange fails or the response is not valid HTTP. It is therefore a proxy-to-application problem, not proof that the browser or the public TLS certificate is broken.

Public HTTPS and the upstream connection are separate. Nginx may terminate TLS for visitors while speaking ordinary HTTP to a Node process on localhost. The upstream should use https:// only when the Node server itself is configured to serve TLS.

#1 Best Overall
Sale
Compressed Air Duster,130000RPM Super Power Cordless Air Duster,Rechargeable Brushless Blower,3 Gear Adjustable Blower with LED Light,Dust Remover for Computer/House/Outdoor/Car
  • Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
  • With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
  • Wide Application:Upgraded attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
  • Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
  • Warranty & Support: Our Electric air duster comes with 5 years warranty and 24/7 customer service. During this period, if you have any questions,pls kindly feel free to contact us.

Start with the nginx error log

The error log normally identifies the failure class faster than inspecting application code. On many Linux distributions the file is /var/log/nginx/error.log; installations can choose another path, so use the error_log directive in the active configuration if that file does not exist.

  1. Open a second terminal and watch the log: sudo tail -f /var/log/nginx/error.log.
  2. In a browser or with curl, request the URL that returns 502.
  3. Match the new log line to the request time, upstream address, and location block handling the request.
Log wording or symptom Likely meaning First check
connect() failed (111: Connection refused) or similar “connection refused” text Nothing is accepting connections at the configured address and port, or the port in nginx is wrong. Check the Node service state and listening socket.
upstream timed out Node did not produce the expected response before the proxy timeout elapsed. Measure the endpoint directly, then investigate slow application work before raising a timeout.
502 with an invalid or malformed upstream response message Something answered, but it did not return a response nginx could parse as HTTP. Call the upstream directly and inspect Node’s output and protocol settings.

Exact wording varies by nginx version and distribution. Treat the examples as diagnostic patterns and confirm the precise message in your installed build. Do not change several unrelated settings before collecting the log line; doing so can hide the original failure.

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

Prove that the Node.js process is alive

Check the process manager

Use the manager that starts your application. For a systemd service, an example is:

sudo systemctl status your-node-service

For a PM2-managed process, inspect its status with:

pm2 status

A failed, stopped, or repeatedly restarting process must be fixed before nginx can proxy to it. Read the service or process-manager log for startup errors such as a missing environment variable, an unavailable database, a failed migration, or an exception during module loading. Restarting nginx cannot bring a crashed Node process back.

Rank #2
EVEO® Screen Cleaner Spray Kit (Streak-Free) TV Screen Cleaner for Smart TV, Lcd, LEd, Oled | Computer Screen Cleaner Spray and Wipe Microfiber Cloth - TV, Monitor, Laptop, iPad, Car - 6.7oz 1 Pack
  • Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
  • Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
  • Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
  • Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
  • Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth

Confirm the listening port

Find the socket that is actually open. If the application is expected on port 3000:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ss -tlnp | grep 3000

The output should show a listening TCP socket and, where permissions allow, the owning process. Compare that port with the number in nginx’s proxy_pass. A common deployment mistake is starting Node with an environment value such as PORT=8080 while leaving nginx pointed at 3000.

Check the bind address

Node must bind to an interface nginx can reach. On the same host, a process listening on 127.0.0.1:3000 is reachable through that loopback address. A process bound only to an unrelated interface is not. If nginx and Node are on different hosts, a loopback address on the Node host is not reachable from the nginx host; use the appropriate private address and firewall rules instead.

Call Node without nginx

A direct request separates application failures from proxy failures:

curl -i http://127.0.0.1:3000/

Use the same path that failed publicly when possible. A normal HTTP status and headers from this command show that Node is answering on that socket; they do not yet prove that nginx is using the same address, port, or URI. A refusal, reset, or hang points to Node, its bind address, or the network path and should be resolved there first.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
BladeHawks RGB Gaming Mouse Pad Extra Large Extended 31.5x12 Inch-Black
  • 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
  • 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
  • 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
  • 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
  • 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.

Use a correct proxy_pass block

For a Node app on the same machine, this is a standard starting point:

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;
}

Replace the port with the one confirmed by ss. The http:// scheme is intentional when Node serves plain HTTP. Nginx can still provide HTTPS to clients; encryption on that public leg does not require HTTPS on the local upstream leg.

Check the address, scheme, and port together

  • Address: it must resolve to an interface where Node is listening.
  • Port: it must match the runtime configuration, not merely the port you intended to use.
  • Scheme: use http:// for a plain-HTTP Node listener and https:// only for a Node listener configured with TLS.

Sending HTTPS to a plain-HTTP Node socket can produce handshake or invalid-response errors that surface as a 502. Conversely, using HTTP for a TLS-only upstream will fail the connection. Test the chosen scheme directly with curl before changing nginx.

Preserve useful request headers

proxy_set_header Host $host; passes the requested host name to Node, which matters when the application selects a tenant or route from the host header. proxy_set_header X-Real-IP $remote_addr; supplies the client address visible to nginx. Keep these directives in the location that handles the failing request so another inherited or competing block does not override them.

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

Understand the proxy_pass URI rule

The presence of a URI portion after the upstream host and port changes how nginx constructs the request sent to Node. This is a frequent source of path errors after a proxy block is copied between applications.

Rank #4
Sale
Vaydeer Wrist Rest for Keyboard and Mouse, Computer Ergonomic Wrist Support Pad, Soft Memory Foam Arm Cushion for Desk, Palm Hand Office Laptop Typing
  • 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
  • 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
  • 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
  • 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
  • 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
Configuration Request from client Path sent upstream
location /api/ { proxy_pass http://127.0.0.1:3000; } /api/users /api/users (the original request URI is retained)
location /api/ { proxy_pass http://127.0.0.1:3000/; } /api/users /users (the matched /api/ prefix is replaced by /)
location / { proxy_pass http://127.0.0.1:3000/app/; } /login The location prefix is replaced with /app/, producing /app/login.

When proxy_pass has no URI part, nginx forwards the request URI as received. When it has a URI part, nginx replaces the portion that matched the location prefix. The trailing slash is therefore significant. Use the examples in the nginx proxy module documentation for complex rewrites rather than inferring behavior from the directive’s wording.

A path mismatch normally causes a Node 404 or application routing error rather than a 502, but it can make a healthy upstream appear broken. Test the exact rewritten path directly with curl and align the location and application router deliberately.

Raise proxy timeouts only when the log shows a timeout

If the error log says upstream timed out, first determine whether the endpoint is legitimately long-running or simply stuck. Compare the direct request to Node with the public request, inspect application and database timings, and check whether the process is CPU- or memory-constrained.

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

The example block uses proxy_read_timeout 60s. Many nginx guides cite 60 seconds as the usual default, but the effective default is version- and configuration-dependent; verify it in the reference for the nginx build you run. If one report or route needs more time, scope the change to that route:

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;
}

Do not raise the timeout globally merely because one request is slow. A larger value keeps client connections open while a failing application consumes resources and can conceal a deadlock or overloaded dependency. Prefer asynchronous jobs, pagination, caching, or application-level performance fixes when the operation does not need to remain synchronous.

Best Value
Sale
Under Desk Cable Management Tray No Drill, Metal Mesh Cable Management Under Desk with Clamp Mount, 2 Hole Cable Tray with Wire Management and Cord Organizer for Home Office Standing Desk
  • 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
  • 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
  • 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
  • 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
  • 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use upstream keepalive deliberately

Under load, repeatedly opening upstream connections can add latency and connection churn. The documented pattern for nginx-to-upstream keepalive uses HTTP/1.1 and removes the hop-by-hop 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 Connection value prevents nginx from sending a Connection: close header to the upstream. Keepalive is a connection-management optimization, not a cure for a stopped process, wrong port, or malformed response. Add it when logs, connection counts, or load behavior indicate churn, and verify that the Node server and any intermediary handle persistent HTTP/1.1 connections correctly.

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

Account for nginx version differences

Nginx’s blog has announced a change in which upstream keepalive became the default, with HTTP/1.1 used by default for HTTP upstreams, starting in version 1.29.7. Confirm that behavior in the release notes and build documentation for your installation; distributions may ship an older or patched version. Before that change, explicitly setting proxy_http_version 1.1 and proxy_set_header Connection "" was the usual way to request this behavior.

Summaries of the upstream module reference have cited an idle keepalive limit of 32 connections per worker process. Treat that figure as version-dependent until verified against your installed reference, and do not size capacity from it without checking worker count, traffic, and upstream limits. Keepalive also interacts with upstream idle timeouts; a backend that closes idle sockets can create errors if connection reuse is misconfigured.

Validate the configuration and reload safely

  1. Test syntax and referenced files: sudo nginx -t.
  2. Do not reload if the test reports an error. Correct the reported file and line first.
  3. Apply a successful configuration with sudo systemctl reload nginx.
  4. Repeat the direct Node request and then test through the nginx hostname: curl -i https://example.com/path (replace the hostname and path with your own).
  5. Watch the error log during the test and confirm that the request reaches the intended upstream.

A reload applies configuration changes without a full nginx restart, allowing existing connections to drain under normal operation. Keep a copy of the last known-good server block so you can restore it quickly if the new location, rewrite, or timeout causes a regression.

Follow the symptom-specific recovery path

“Connection refused” after a deployment

  1. Check the Node service or PM2 process state.
  2. Read its startup log for crashes and missing configuration.
  3. Run ss -tlnp and record the actual address and port.
  4. Make proxy_pass match that socket, or fix the application’s PORT and bind settings.
  5. Call the socket with curl, then run nginx -t and reload.

“Upstream timed out” on one endpoint

  1. Call the endpoint directly on the Node port and measure how long it takes.
  2. Inspect application, database, and external-service timings.
  3. Fix the slow operation if it should be fast.
  4. If the duration is intentional, set a larger proxy_read_timeout only on that location and document why.
  5. Retest under representative concurrency rather than relying on a single request.

Node works locally but the public URL still returns 502

  • Confirm that nginx is loading the server block you edited, not another file or virtual host.
  • Check that the public location matches the request path and that a more specific location is not selecting a different upstream.
  • Compare the address in the log with the address tested by curl.
  • Check the upstream scheme for an HTTP-versus-HTTPS mismatch.
  • Run sudo nginx -t and reload after every accepted change.

The error began after adding a trailing slash

Inspect the resulting URI, not just the status code. A slash in proxy_pass can remove the location prefix before the request reaches Node. If the application expects /api/users but receives /users, either remove the URI portion or adjust the Node route intentionally. A direct curl request to both candidate paths makes the difference visible.

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.

Failures are intermittent under load

Check whether Node is restarting, exhausting file descriptors, or taking longer as concurrency rises. Correlate nginx error-log timestamps with process-manager events. If the failures coincide with a high rate of short-lived upstream connections, evaluate HTTP/1.1 keepalive and the empty Connection header, while also checking backend idle timeouts. Do not treat keepalive as a substitute for capacity planning or application health checks.

A repeatable production checklist

  • Record the exact nginx error line for a failed request.
  • Verify the Node process is running and not restarting.
  • Verify the listening address and port with ss -tlnp.
  • Request the same endpoint directly from the upstream socket.
  • Match proxy_pass address, port, and scheme to that socket.
  • Check whether a URI portion and trailing slash rewrite the path your router expects.
  • Change proxy_read_timeout only for logged upstream timeouts.
  • Configure keepalive only when connection churn or load behavior warrants it, and account for nginx version defaults.
  • Run sudo nginx -t before every reload.
  • Reload with sudo systemctl reload nginx, then test through nginx while watching the log.

The Bottom Line

Fix an nginx 502 by proving the upstream path one link at a time: identify the logged failure, make sure Node is listening on the configured socket, test it directly, correct proxy_pass and URI behavior, and only then tune timeouts or keepalive. Validate with nginx -t and reload rather than restarting blindly.

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.