0
0
NginxDebug / FixBeginner · 3 min read

How to Fix 502 Bad Gateway Error in Nginx Quickly

A 502 Bad Gateway error in Nginx happens when Nginx cannot get a valid response from the backend server. To fix it, check if your backend service (like PHP-FPM or an app server) is running and correctly configured in your nginx.conf or site config files.
🔍

Why This Happens

A 502 Bad Gateway error means Nginx tried to contact a backend server but got an invalid or no response. This usually happens if the backend server is down, misconfigured, or unreachable.

Common causes include backend service crashes, wrong socket or port in Nginx config, or firewall blocking connections.

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:9000;  # Backend server port
    }
}
Output
502 Bad Gateway nginx/1.24.0
🔧

The Fix

First, make sure your backend service is running on the expected port or socket. For example, if using PHP-FPM, check it is active.

Then, update your Nginx config to point to the correct backend address. Restart Nginx after changes.

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;  # Correct backend port
    }
}
Output
Nginx serves the site without 502 errors.
🛡️

Prevention

To avoid 502 errors in the future:

  • Regularly monitor backend services to ensure they are running.
  • Use health checks and automatic restarts for backend processes.
  • Validate Nginx configuration with nginx -t before reloading.
  • Keep backend and Nginx logs handy to quickly spot issues.
⚠️

Related Errors

Other common Nginx errors include:

  • 504 Gateway Timeout: Backend took too long to respond. Fix by increasing timeout or optimizing backend.
  • 500 Internal Server Error: Backend crashed or misconfigured. Check backend logs.

Key Takeaways

A 502 error means Nginx can't get a valid response from the backend server.
Check that your backend service is running and reachable on the configured port or socket.
Correct your Nginx proxy_pass or fastcgi_pass settings to match the backend address.
Use nginx -t to test config before reloading to prevent errors.
Monitor backend health and logs to catch issues early and avoid 502 errors.