What is a 502 Bad Gateway Error?
In web development, the HTTP status code 502 indicates that a server acting as a gateway or proxy received an invalid response from an upstream server. When using Nginx as a reverse proxy or load balancer, a 502 error typically means Nginx could not get a proper response from the backend server it’s trying to reach. This could be a PHP-FPM service, a Node.js app, another web server, or a microservice.
Common scenarios include:
- Upstream server crashed or not running
- Network connectivity issues (firewall, incorrect port)
- Backend server taking too long to respond (timeout)
- Backend server returning malformed data
- Nginx buffer sizes too small for large headers
- Misconfigured socket or permissions
Why Fixing the 502 Error Matters
🚀 Deploy your AI agent in 10 minutes
Managed Hermes hosting. Zero DevOps. 100M tokens/mo included.
Try it free →A 502 error directly impacts user experience, breaking the functionality of your website or API. Frequent 502s can harm SEO, erode trust, and cause revenue loss. For developers, it's a critical alert that the system architecture is failing. Proper diagnosis and resolution not only restores service but also improves the reliability of your infrastructure.
How to Diagnose and Fix the Nginx 502 Error
1. Check Upstream Service Status
The first step is to verify that the backend service Nginx is proxying to is actually running and listening on the expected port or socket.
For PHP-FPM (common with WordPress, Laravel):
# Check if PHP-FPM is running
sudo systemctl status php7.4-fpm # or php-fpm depending on version
# If not running, start it
sudo systemctl start php7.4-fpm
# Verify listening socket or port
sudo ss -plnt | grep 9000 # TCP port 9000 default for some setups
ls -l /var/run/php/php7.4-fpm.sock # Check socket file
For a Node.js or Python backend running on port 3000:
# Check if the process is running
ps aux | grep node
# Or use systemd status
sudo systemctl status myapp
# Test the port
curl -I http://localhost:3000
2. Verify Nginx Configuration for Upstream
Incorrect upstream address, port, or socket path in the Nginx config will cause a 502. Check the proxy_pass or fastcgi_pass directives.
Example for a FastCGI (PHP-FPM) configuration:
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # Must match actual socket
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
Ensure the socket path exists and Nginx has read/write permissions (often user www-data).
For reverse proxy to a backend service:
location /api/ {
proxy_pass http://127.0.0.1:3000; # Correct IP and port
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
3. Increase Timeout Values
If the backend needs more time to process requests, Nginx may close the connection prematurely. Adjust timeout directives in the Nginx configuration.
location /api/ {
proxy_pass http://backend;
proxy_read_timeout 120s; # Wait for response
proxy_connect_timeout 60s; # Time to establish connection
proxy_send_timeout 60s;
}
For FastCGI (PHP):
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php-fpm.sock;
fastcgi_read_timeout 300s; # Increase for long-running scripts
fastcgi_send_timeout 300s;
}
4. Adjust Buffer Sizes for Large Responses
If the backend sends large headers or cookies exceeding default Nginx buffers, Nginx returns a 502. Increase buffer settings:
location / {
proxy_pass http://backend;
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
# For FastCGI
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
}
5. Check Firewall and SELinux
If the backend is on a different server, a firewall might block the connection. On the backend server, ensure the port is open:
sudo firewall-cmd --add-port=3000/tcp --permanent
sudo firewall-cmd --reload
# Or with iptables
sudo iptables -A INPUT -p tcp --dport 3000 -j ACCEPT
SELinux can prevent Nginx from connecting to network ports or sockets. Temporarily test with:
sudo setenforce 0 # Set to permissive
# If error disappears, adjust policy:
sudo setsebool -P httpd_can_network_connect on # For proxy to network
# For socket permissions, restore correct context
sudo restorecon -Rv /var/run/php/
6. Check Backend Error Logs
Nginx logs provide clues, but also examine the backend application logs. For PHP-FPM:
# PHP-FPM error log location
sudo tail -f /var/log/php7.4-fpm.log
# Or check your pool configuration's error_log
For a Node.js app, look at its stdout/stderr. If the app crashes, it won't respond, causing 502.
7. Handle Keepalive and Connection Limits
Too many concurrent connections can overwhelm the backend, leading to dropped connections and 502 errors. Configure upstream keepalive and worker connections.
upstream backend {
server 127.0.0.1:3000;
keepalive 16; # Keep connections open for reuse
}
server {
location / {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
8. Verify DNS Resolution (If Using Hostnames)
If proxy_pass uses a hostname that fails to resolve, Nginx returns 502. Use an IP or ensure the resolver is configured:
resolver 8.8.8.8 valid=300s;
resolver_timeout 5s;
location / {
proxy_pass http://api.example.com; # Hostname
}
Best Practices to Prevent 502 Errors
- Monitor backend health: Use Nginx's health_check (NGINX Plus) or external monitoring to restart failed services automatically.
- Implement graceful degradation: Use a static error page (like a custom 502 page) to inform users without breaking the experience.
- Optimize backend performance: Ensure your backend can handle peak loads without timing out. Use caching, queue long tasks.
- Keep configuration in sync: Use configuration management (Ansible, Chef) to ensure socket paths and ports match across Nginx and backends.
- Set proper timeouts and buffers: Tune based on your application’s expected response times and header sizes.
- Use Unix sockets for local services: Sockets are faster and avoid network overhead, but ensure permissions are correct.
- Test after changes: Always reload Nginx with
nginx -tto check syntax, thensystemctl reload nginx.
Conclusion
The Nginx 502 Bad Gateway error is a signal that your gateway cannot communicate effectively with an upstream server. By systematically checking service status, configuration correctness, network connectivity, timeouts, buffer limits, and logs, you can pinpoint the root cause and apply the fix. Adopting best practices like health checks, proper tuning, and consistent configuration will minimize the occurrence of 502 errors and keep your web applications running reliably.