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 Nginx accepted the browser request but could not get a usable response from the Gunicorn endpoint configured in proxy_pass. The fault is usually a stopped Gunicorn service, a mismatched Unix socket or TCP port, socket permissions, a failed worker, or an incorrect proxy protocol. Find the exact upstream error first, then test the same endpoint as Nginx before changing application code.

What a 502 means in an Nginx–Gunicorn deployment

Nginx is the reverse proxy and Gunicorn is the upstream application server. A request normally travels through this chain:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. The client connects to Nginx.
  2. Nginx selects a location block and follows its proxy_pass target.
  3. Nginx connects to Gunicorn over a Unix socket or TCP address.
  4. Gunicorn assigns the request to a worker and returns an HTTP response.
  5. Nginx sends that response to the client.

A 502 indicates that the handoff in steps 3 or 4 failed. It does not, by itself, prove that your application route is broken. Gunicorn can be running while listening on a different socket, port, or address, and it can also be starting workers that immediately exit. The Gunicorn deployment documentation states: “We strongly recommend running Gunicorn behind a proxy server.” That arrangement works only when both processes agree on the same endpoint and protocol.

Capture the exact failure before changing configuration

Start with the Nginx error log. Its message normally identifies whether the problem is connection refusal, a missing socket, permissions, a timeout, or an invalid upstream response.

#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.
sudo tail -f /var/log/nginx/error.log

In another terminal, reproduce the failing URL. Typical messages include:

  • connect() failed (111: Connection refused) while connecting to upstream: nothing is listening at the configured TCP address, or Gunicorn is listening elsewhere.
  • connect() to unix:/path/gunicorn.sock failed (2: No such file or directory): the socket was not created, was removed during a restart, or the path in Nginx is wrong.
  • connect() to unix:/path/gunicorn.sock failed (13: Permission denied): the Nginx worker cannot traverse the directory or access the socket.
  • A timeout while connecting or reading: Gunicorn may be overloaded, blocked, bound to an unreachable address, or unable to complete the request.
  • An invalid or prematurely closed response: a worker may have crashed, or Nginx and the upstream are using incompatible protocol settings.

Then inspect the Gunicorn service and its recent logs. Replace gunicorn with the actual systemd unit name if your deployment uses a different one.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo systemctl status gunicorn
sudo journalctl -u gunicorn -n 100 --no-pager

Look for import errors, a failure to bind, a missing working directory, an invalid executable path, configuration errors, and workers that start and immediately exit. Gunicorn’s FAQ notes that a reverse proxy can report 502 while Gunicorn shows only worker-startup messages, so inspect both logs rather than relying on the application log alone.

Make Nginx and Gunicorn use the same endpoint

Compare the address in Nginx with Gunicorn’s --bind setting or its systemd ExecStart command. The endpoint must match in path, address, port, and transport.

Unix-socket configuration

A Unix socket is a filesystem object, commonly placed under /run or /tmp. Gunicorn can bind to a path such as /tmp/gunicorn.sock, while Nginx names that socket in an upstream block:

upstream app_server {
    server unix:/tmp/gunicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name example.test;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://app_server;
    }
}

The corresponding Gunicorn bind might be --bind unix:/tmp/gunicorn.sock. A one-character difference in the path creates a different socket and produces a 502 even when Gunicorn is healthy.

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.
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

TCP configuration

For TCP, Gunicorn listens on an IP address and port, for example 192.168.0.7:8000. Nginx can define that listener in the upstream group and proxy to the group name:

upstream app_server {
    server 192.168.0.7:8000;
}

location / {
    proxy_pass http://app_server;
}

Gunicorn must bind to the same address and port. Binding only to 127.0.0.1:8000 will not work if Nginx is on another host, and binding to a private interface will not work if Nginx resolves a different address.

Deployment choice What must match Typical failure Operational trade-off
Unix socket Exact filesystem path, directory traversal, owner, group, and mode Missing socket or permission denied No network port is exposed, but the socket lifecycle and filesystem permissions must be maintained
TCP listener IP address, port, routing, and firewall policy Connection refused or unreachable upstream Simpler path handling and suitable for separate hosts, but address and network access must be controlled

Test the upstream as the Nginx user

A test made as root can hide the very permission problem that causes the 502. If the deployment uses the usual www-data Nginx account and a socket at /run/gunicorn.sock, run:

sudo -u www-data curl --unix-socket /run/gunicorn.sock http

Use the path requested by your application when necessary. A valid HTTP response, even a framework-level 404, proves that the account can open the socket and that Gunicorn is answering. A connection error means the fault is below Nginx routing: fix Gunicorn, the socket path, ownership, group membership, or mode first.

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

For a TCP listener, test the same address and port from the Nginx host:

curl -v http://192.168.0.7:8000/

If this direct request fails, changing proxy_set_header or application routes will not solve the 502. If it succeeds but the proxied request fails, focus on the Nginx upstream definition, the Nginx worker’s identity, and the request protocol.

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.

Repair systemd socket activation

With socket activation, systemd creates and owns the listening socket, then starts Gunicorn when the socket receives traffic. A representative socket unit is:

[Unit]
Description=Gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock
SocketUser=www-data
SocketGroup=www-data
SocketMode=0660

[Install]
WantedBy=sockets.target

Enable and start it with:

sudo systemctl enable --now gunicorn.socket

Check the resulting object and unit state:

sudo systemctl status gunicorn.socket
ls -l /run/gunicorn.sock

The service unit should require the socket and start Gunicorn with the intended working directory and executable. Its unit section commonly includes:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
[Unit]
Requires=gunicorn.socket
After=network.target

Verify that the service’s WorkingDirectory, virtual-environment path, application module, and worker command are correct. An import error or an executable path from a deleted virtual environment can make the service fail even though the socket unit is active.

Socket activation also explains the common symptom “the socket exists, but Nginx still gets 502.” The file can exist while no healthy Gunicorn process is accepting requests, or it can have an owner and mode that prevent Nginx from opening it. Inspect both gunicorn.socket and gunicorn.service; restarting only the service may not recreate a damaged socket. If the path is recreated during a restart, confirm that systemd applies the expected owner, group, and mode every time.

Fix Unix-socket permissions and confinement

Nginx needs two kinds of access:

  • Execute (traverse) permission on every parent directory in the socket path.
  • Read/write access to the socket itself according to its owner, group, and mode.

Inspect each directory and the socket:

namei -l /run/gunicorn.sock
ls -l /run/gunicorn.sock

Confirm the Nginx worker account. It is set by the user directive in the main Nginx configuration and may differ from www-data. The socket’s SocketUser, SocketGroup, and SocketMode must allow that account to connect. A mode of 0660 works only when Nginx belongs to the socket’s group (or is the owner).

Do not solve the problem by making the socket or its parent directories world-writable. Correct the systemd ownership and group, use a directory intended for runtime sockets, and ensure the service recreates the object consistently. If mandatory access controls or another confinement system is enabled, inspect its denial logs as well as normal Unix permissions; a path that looks accessible with ls can still be blocked by policy.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Set the proxy headers and protocol deliberately

Gunicorn and the application need to know the original host, client chain, and scheme when Nginx terminates the public connection. A typical location includes:

proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

Use an appropriate Host value for your application. Forwarding the original host supports virtual-host routing and URL generation; forwarding the scheme prevents an HTTPS request from being treated as plain HTTP. The forwarded-for setting preserves the existing client chain while adding Nginx’s address.

When Nginx and Gunicorn run on different hosts, do not trust forwarded headers from every possible client. Restrict Gunicorn’s trusted forwarded-header sources to the proxy addresses. Otherwise an external client could supply a forged scheme or client address. Header mistakes more often cause redirects, incorrect absolute URLs, or security issues than a direct 502, but correcting them is part of a sound proxy handoff.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use buffering that matches the worker model

For ordinary request/response traffic handled by synchronous workers, keep Nginx proxy buffering enabled. It lets Nginx absorb the upstream response and protects the client connection from tying up a Gunicorn worker unnecessarily.

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

Streaming responses, server-sent events, and long-polling need different behavior. For those patterns, the deployment guidance calls for an asynchronous Gunicorn worker class and disabled proxy buffering:

location /stream/ {
    proxy_buffering off;
    proxy_pass http://app_server;
}
Traffic pattern Gunicorn workers Nginx buffering Reason
Normal short requests Synchronous workers Keep enabled Default request handling and response buffering
Streaming or long-polling Asynchronous worker class Turn off for the streaming location Allows incremental data to reach the client instead of waiting for a complete buffered response

Disabling buffering is not a general cure for a connection-refused 502. First establish that Nginx can connect and Gunicorn can answer; then tune buffering for the endpoint’s traffic pattern.

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.

Validate configuration and retest in a controlled order

After making one related change, validate Nginx before reloading it. The exact binary path varies by distribution, but the standard test is:

sudo nginx -t

Only after a successful test should you reload Nginx:

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

Restart only the changed Gunicorn service or socket unit, rather than restarting the entire server:

sudo systemctl restart gunicorn
sudo systemctl restart gunicorn.socket

Use the command appropriate to the component you changed; restarting both is useful when repairing socket activation, but unnecessary restarts can erase useful diagnostic state. Tail the Nginx and Gunicorn logs while requesting the failing URL. Confirm in this order:

  1. Gunicorn starts without import, bind, or worker-exit errors.
  2. The expected Unix socket or TCP listener exists.
  3. The Nginx account can make a direct request to that endpoint.
  4. nginx -t passes and Nginx reloads cleanly.
  5. The public URL returns the application’s response while both logs remain free of upstream errors.

A successful direct socket or TCP curl followed by a successful proxied request demonstrates that the original fault was in Nginx routing, permissions, or service wiring rather than the application endpoint itself.

Choose the right fix from the symptom

Observed symptom Most likely cause Next check
Connection refused to an IP and port Gunicorn is stopped, bound to another port, or listening only on another interface Compare --bind with proxy_pass; inspect service status and listening sockets
No such file for a Unix socket Wrong path or socket not recreated after restart Compare the systemd ListenStream and Nginx upstream path; inspect socket-unit state
Permission denied Nginx cannot traverse a parent directory or open the socket Run the Unix-socket curl as the Nginx account; inspect namei -l and socket ownership
Socket exists but requests fail Gunicorn service is unhealthy, workers exit, or the socket belongs to a stale listener Read the Gunicorn journal and test the socket directly
Direct upstream curl works, public URL fails Nginx upstream block, location matching, headers, or reload state is wrong Run nginx -t, verify the selected location, reload, and watch the error log
Streaming endpoint stalls or closes unexpectedly Buffered proxying or synchronous workers are unsuitable for the traffic pattern Use an asynchronous worker class and disable buffering only for the streaming location

A compact recovery checklist

  • Record the complete Nginx upstream error while reproducing the 502.
  • Check the Gunicorn systemd status and recent journal entries for startup and worker failures.
  • Write down the exact Gunicorn bind address or socket path.
  • Compare it character-for-character with Nginx’s upstream and proxy_pass.
  • Test the endpoint as the Nginx worker account, not only as root.
  • For systemd sockets, verify ListenStream, ownership, group, mode, and the service’s Requires relationship.
  • Check directory traversal, mandatory confinement, and socket recreation after restarts.
  • Set the host and forwarded headers deliberately, and limit trusted proxy sources when hosts are separate.
  • Keep buffering for synchronous ordinary requests; disable it only for streaming patterns with asynchronous workers.
  • Run nginx -t, reload Nginx, restart the changed unit, and retest while tailing both logs.

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.

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.