Error Medic

How to Fix 502 Bad Gateway and 504 Gateway Time Out Errors in Nginx

Master Nginx 502 Bad Gateway and 504 Gateway Time Out errors. Learn to diagnose upstream timeouts, adjust proxy_pass settings, and fix backend crashes.

Last updated:
Last verified:
1,890 words
Key Takeaways
  • A 502 Bad Gateway indicates Nginx cannot reach the upstream backend (e.g., Node.js, PHP-FPM) or received an invalid/corrupt response.
  • A 504 Gateway Time Out occurs when the backend server takes too long to respond, breaching Nginx's proxy_read_timeout or fastcgi_read_timeout limits.
  • The absolute first step in diagnosis is checking /var/log/nginx/error.log for specific OS-level error codes like '111: Connection refused' or '110: Connection timed out'.
  • Quick fixes involve restarting the backend service or temporarily increasing Nginx and PHP/Node timeout directives.
  • Permanent resolution requires addressing the backend application bottleneck: optimizing database queries, utilizing background worker queues, or allocating more system resources.
Common Fix Approaches Compared
MethodWhen to UseTime RequiredRisk Level
Restart Upstream ServiceBackend service crashed, hung, or ran out of memory (e.g., PHP-FPM, PM2/Node.js)1-2 minsLow
Increase Nginx TimeoutsLegitimate slow requests (e.g., heavy WordPress exports, complex reporting queries)5 minsMedium (may mask underlying performance issues)
Fix PHP/Node Resource LimitsWorkers exhausted, max_execution_time hit, or OOM (Out of Memory) kills in backend15 minsLow
Correct Socket PermissionsNginx logs show '13: Permission denied' when connecting to a Unix socket10 minsLow

Understanding the Architecture of Nginx Gateway Errors

To effectively troubleshoot a 502 bad gateway nginx or 504 gateway time out nginx error, it is crucial to understand Nginx's role in modern web architecture. In most production environments, Nginx does not execute application code itself. Instead, it operates as a reverse proxy. It accepts incoming HTTP requests from clients (browsers), processes SSL termination and static file delivery, and then forwards dynamic requests to an "upstream" application server. This upstream server could be a Node.js process, a PHP-FPM worker, a Python Gunicorn server, or a Java Tomcat container.

Gateway errors occur when the communication between Nginx (the gateway) and the upstream application server breaks down.

What is a 502 Bad Gateway?

The HTTP 502 Bad Gateway status code means Nginx acted as a gateway or proxy and received an invalid response from the upstream server. In practice, "invalid response" usually means no response at all. The upstream server either actively refused the connection, crashed midway through processing the request, or the network routing between Nginx and the upstream server is misconfigured.

What is a 504 Gateway Time Out?

The HTTP 504 nginx gateway timeout status code means Nginx successfully connected to the upstream server, passed the request, and then waited... and waited. Every proxy configuration in Nginx has a defined timeout limit. If the upstream server (e.g., WordPress or Node.js) takes longer to process the request than Nginx is configured to wait, Nginx will sever the connection and return a 504 error to the client.

This is incredibly common in scenarios like generating large CSV exports, processing image uploads in WordPress, or waiting for third-party API responses in a Node.js backend.


Step 1: Diagnose the Error Logs

Do not guess. The exact reason for an nginx response timeout or gateway failure is always documented in the Nginx error logs.

SSH into your server and run:

tail -n 50 /var/log/nginx/error.log

You will typically see one of three critical error patterns:

Pattern 1: Connection Refused (502)

connect() failed (111: Connection refused) while connecting to upstream

This means Nginx tried to forward the request, but nothing is listening on the target port (e.g., 127.0.0.1:8080 or 127.0.0.1:3000). Your backend service (Node.js, PHP, etc.) is likely down, crashed, or configured to listen on the wrong port.

Pattern 2: Permission Denied (502)

connect() to unix:/var/run/php/php8.1-fpm.sock failed (13: Permission denied)

If you are using Unix sockets instead of TCP ports to connect to your backend (common for PHP-FPM), this means Nginx does not have file system permissions to read/write to the socket file. This often happens after an OS upgrade or user permission change.

Pattern 3: Upstream Timed Out (504)

upstream timed out (110: Connection timed out) while reading response header from upstream

This is the classic nginx upstream timed out 504 error. The upstream server accepted the request but failed to generate a response within the allotted time (typically 60 seconds by default).


Step 2: Fixing 502 Bad Gateway

If your logs indicate a 502 error, your focus must be on the upstream service's health and connectivity.

1. Verify the Upstream Service is Running

If you are running a Node.js application (often associated with 504 gateway time out nginx nodejs but equally prone to 502s if crashed):

pm2 status
# or
systemctl status my-node-app

If you are running WordPress or another PHP application:

systemctl status php8.1-fpm

If the service is inactive or failed, restart it (systemctl restart php8.1-fpm). If it crashes immediately, check the specific application logs (e.g., /var/log/php8.1-fpm.log or PM2 logs) to fix the fatal application error.

2. Verify Port and Socket Configurations

Check your Nginx proxy_pass or fastcgi_pass directive. If Nginx is configured with proxy_pass http://127.0.0.1:3000;, ensure your Node.js application is actually binding to port 3000 and not 8080.

3. Fix Socket Permissions

If using a Unix socket, ensure the user running Nginx (usually www-data or nginx) has permissions to access the socket. In your PHP-FPM pool configuration (e.g., /etc/php/8.1/fpm/pool.d/www.conf), verify:

listen.owner = www-data
listen.group = www-data
listen.mode = 0660

Step 3: Fixing 504 Gateway Time Out

If you are encountering a 504 gateway time out nginx error, the backend application is taking too long. You have two paths: treat the symptom (increase the timeout) or cure the disease (optimize the application).

Approach A: Increasing Nginx Timeouts (The Quick Fix)

If you have a legitimate process that simply takes a long time (like a data migration or a massive WooCommerce product import causing a 504 gateway time out nginx wordpress error), you need to increase the Nginx timeout directives.

For reverse proxies (Node.js, Python, Java), edit your Nginx configuration (e.g., /etc/nginx/sites-available/default) and add/modify these values within your location / block:

location / {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    
    # The crucial timeout settings:
    proxy_connect_timeout 300s;
    proxy_send_timeout 300s;
    proxy_read_timeout 300s;
}
  • proxy_connect_timeout: Time allowed to establish a connection to the upstream.
  • proxy_send_timeout: Time allowed to transmit a request to the upstream.
  • proxy_read_timeout: Time allowed to read a response from the upstream. This is the most common culprit for 504 errors.

For FastCGI backends (PHP-FPM / WordPress), the directives are different. Update your location ~ \.php$ block:

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
    
    # Increase FastCGI timeouts
    fastcgi_connect_timeout 300s;
    fastcgi_send_timeout 300s;
    fastcgi_read_timeout 300s;
}

Crucial Step for PHP/WordPress: Increasing Nginx's timeout is useless if PHP itself times out first. You must also edit your php.ini file (e.g., /etc/php/8.1/fpm/php.ini):

max_execution_time = 300
max_input_time = 300

After making these changes, reload both services: systemctl reload php8.1-fpm and systemctl reload nginx.

Approach B: Fixing the Root Cause (The Long-Term Solution)

Increasing timeouts to 5 or 10 minutes is an anti-pattern for standard web requests. If your users are waiting 60+ seconds for a page load, they will abandon the site long before the 504 error appears.

To truly fix gateway timeout 504 nginx issues:

  1. Optimize Database Queries: A slow MySQL or PostgreSQL query is the #1 cause of upstream delays. Use slow query logs to identify bottlenecks and add appropriate indexes.
  2. Use Background Processing: If a user action triggers a long-running task (sending 10,000 emails, generating a PDF), do not process it synchronously in the web request. Offload the task to a background queue like Redis + Celery (Python), BullMQ (Node.js), or Laravel Horizon (PHP), and return a 202 Accepted response to the user immediately.
  3. Scale Resources: Your backend server might be starved for CPU or RAM, causing the Node.js event loop to lag or PHP workers to thrash. Monitor htop during traffic spikes.

Platform and Version Specifics

Many users search for specific version combinations like 504 gateway time out nginx 1.18 0 ubuntu or 504 gateway time out nginx 1.20 2.

The good news is that the core architecture of Nginx proxying has remained remarkably stable. Whether you are running Nginx 1.10.3 on legacy Ubuntu 16.04, Nginx 1.18.0 on Ubuntu 20.04, or Nginx 1.21.6 on Ubuntu 22.04, the timeout directives (proxy_read_timeout, fastcgi_read_timeout) and troubleshooting steps are identical.

However, newer versions introduced better handling for HTTP/2 and gRPC. If you are reverse proxying a gRPC service and experiencing timeouts, you will need to adjust grpc_read_timeout and grpc_send_timeout specifically.

Nginx SSL Handshake Timeout

A related but distinct issue is the nginx ssl handshake timeout. This occurs between the client and Nginx, not Nginx and the upstream. It means the client's browser took too long to complete the TLS/SSL negotiation. This is usually caused by extremely poor client network connections or severe packet loss. You can mitigate this slightly by tweaking ssl_session_timeout and enabling SSL session caching in your Nginx config, but it is rarely an issue with your backend application.

Frequently Asked Questions

bash
# 1. Tail the Nginx Error Logs to find the exact root cause
tail -f /var/log/nginx/error.log

# 2. Check the status of your upstream backend service
systemctl status php8.1-fpm  # For PHP/WordPress
systemctl status nodejs      # For Systemd Node apps
pm2 status                   # For PM2 managed Node apps

# 3. Nginx Configuration to Increase Proxy Timeouts
# Edit /etc/nginx/sites-available/default and add these to your location block:
# 
# location / {
#     proxy_pass http://localhost:3000;
#     proxy_connect_timeout 300s;
#     proxy_send_timeout 300s;
#     proxy_read_timeout 300s;
# }

# 4. Validate Nginx config syntax and reload gracefully
nginx -t
systemctl reload nginx
E

Error Medic Editorial

Our team of Senior Site Reliability Engineers (SREs) and Systems Administrators specialize in Linux infrastructure, Nginx performance tuning, and highly available web architectures.

Sources

Related Articles in Nginx

Explore More Networking Guides